package com.zioinfo.mes.auth;

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

import java.util.Map;

/**
 * MES 인증 컨트롤러.
 * - /login: 2FA off 면 { token, type, twofa:"false" }, 2FA on 이면 { twofa:"true", verifyToken, step, maskedEmail }.
 * - /verify: (UIWS 2FA 이식) verify-token + 인증코드 → access/refresh 발급.
 * 기존 클라이언트(2FA off)는 응답 형태 token 보존 → 회귀 0.
 */
@RestController
@RequestMapping("/api/mes/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/refresh 발급. */
    @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, Object>> me(@RequestHeader("Authorization") String header) {
        String token = header.replace("Bearer ", "");
        return ApiResponse.ok(authService.me(token));
    }

    record LoginRequest(String username, String password) {}

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