package com.zioinfo.signage.auth;

import com.zioinfo.signage.common.ApiResponse;
import com.zioinfo.signage.uiws.auth.TwoFactorService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * ESN 인증 컨트롤러.
 * - /login: 2FA off 면 { twofa:"false", token, type }, 2FA on 이면 { twofa:"true", verifyToken, step, maskedEmail }.
 * - /verify: (UIWS 2FA 이식) verify-token + 인증코드 → access 토큰 발급.
 * 기존 클라이언트는 응답에 token 필드가 그대로 존재(2FA off 시) → 회귀 0.
 */
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;
    private final TwoFactorService twoFactorService;

    @PostMapping("/login")
    public ApiResponse<Map<String, String>> login(@RequestBody LoginRequest req) {
        return ApiResponse.ok(authService.login(req.username(), req.password()));
    }

    /** UIWS 2FA 이식: 2차 인증 코드 검증 → access 토큰 발급. */
    @PostMapping("/verify")
    public ApiResponse<Map<String, String>> verify(@RequestBody VerifyRequest req) {
        return ApiResponse.ok(twoFactorService.verify(req.verifyToken(), req.code()));
    }

    @GetMapping("/me")
    public ApiResponse<Map<String, String>> me(@RequestHeader("Authorization") String header) {
        String token = header.replace("Bearer ", "");
        return ApiResponse.ok(authService.me(token));
    }

    @PostMapping("/logout")
    public ApiResponse<Void> logout() {
        // JWT stateless — 클라이언트에서 토큰 삭제
        return ApiResponse.ok("로그아웃 성공", null);
    }

    record LoginRequest(String username, String password) {}

    record VerifyRequest(String verifyToken, String code) {}
}
