package com.ga.api.auth;

import com.ga.common.model.ApiResponse;
import com.ga.core.vo.user.UserResp;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@Tag(name = "인증")
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;

    @PostMapping("/login")
    public ApiResponse<LoginResp> login(@Valid @RequestBody LoginReq req, HttpServletRequest http) {
        return ApiResponse.ok(authService.login(req, ipOf(http), http.getHeader("User-Agent")));
    }

    @PostMapping("/refresh")
    public ApiResponse<LoginResp> refresh(@Valid @RequestBody RefreshTokenReq req) {
        return ApiResponse.ok(authService.refresh(req.getRefreshToken()));
    }

    @GetMapping("/me")
    public ApiResponse<UserResp> me() {
        return ApiResponse.ok(authService.me());
    }

    @PostMapping("/password")
    public ApiResponse<Void> changePassword(@Valid @RequestBody ChangePasswordReq req) {
        authService.changePassword(req.getOldPassword(), req.getNewPassword());
        return ApiResponse.ok();
    }

    @PostMapping("/logout")
    public ApiResponse<Void> logout() {
        authService.logout();
        return ApiResponse.ok();
    }

    private String ipOf(HttpServletRequest req) {
        String xf = req.getHeader("X-Forwarded-For");
        if (xf != null && !xf.isBlank()) return xf.split(",")[0].trim();
        return req.getRemoteAddr();
    }
}
