package gc.mda.kcg.auth;

import gc.mda.kcg.auth.dto.AuthResponse;
import gc.mda.kcg.auth.dto.GoogleAuthRequest;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private static final String JWT_COOKIE_NAME = "kcg_token";

    private final AuthService authService;
    private final JwtProvider jwtProvider;

    /**
     * Google OAuth2 id_token 검증 후 JWT 쿠키 발급
     */
    @PostMapping("/google")
    public ResponseEntity<AuthResponse> googleLogin(
            @Valid @RequestBody GoogleAuthRequest request,
            HttpServletResponse response) {

        AuthResponse authResponse = authService.authenticateWithGoogle(request.getCredential());
        String token = jwtProvider.generateToken(authResponse.getEmail(), authResponse.getName());

        Cookie cookie = new Cookie(JWT_COOKIE_NAME, token);
        cookie.setHttpOnly(true);
        cookie.setSecure(false);
        cookie.setPath("/");
        cookie.setMaxAge((int) (jwtProvider.getExpirationMs() / 1000));
        response.addCookie(cookie);

        return ResponseEntity.ok(authResponse);
    }

    /**
     * JWT 쿠키에서 현재 사용자 정보 반환
     */
    @GetMapping("/me")
    public ResponseEntity<AuthResponse> me(
            @CookieValue(name = JWT_COOKIE_NAME, required = false) String token) {

        if (token == null || token.isBlank()) {
            return ResponseEntity.status(401).build();
        }

        AuthResponse authResponse = authService.getUserFromToken(token);
        return ResponseEntity.ok(authResponse);
    }

    /**
     * JWT 쿠키 삭제 (로그아웃)
     */
    @PostMapping("/logout")
    public ResponseEntity<Void> logout(HttpServletResponse response) {
        Cookie cookie = new Cookie(JWT_COOKIE_NAME, "");
        cookie.setHttpOnly(true);
        cookie.setSecure(false);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        return ResponseEntity.ok().build();
    }
}
