package com.zioinfo.mall.auth;

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

import java.util.Map;

/**
 * GUARDiA Mall 인증 컨트롤러.
 * - /login: 고객(USER)·2FA off → { token }. 운영(ADMIN/MANAGER)+2FA on → { twofa:"true", verifyToken, step, maskedEmail }.
 * - /verify: (UIWS 2FA 이식) verify-token + 인증코드 → access 발급. 운영 로그인 2단계 완료용.
 * 기존 고객 클라이언트(token 응답)는 형태 보존 → 쇼핑 로그인 회귀 0.
 */
@RestController
@RequestMapping("/api/mall/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()));
    }

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

    /** 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));
    }

    record LoginRequest(String username, String password) {}
    record RegisterRequest(String username, String password, String displayName) {}
    record VerifyRequest(String verifyToken, String code) {}
}
