package com.mosquito.project.controller;

import com.mosquito.project.dto.ApiResponse;
import com.mosquito.project.dto.LoginRequest;
import com.mosquito.project.dto.LoginResponse;
import com.mosquito.project.service.AuthService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 登录认证控制器 - 独立登录认证
 */
@RestController
@RequestMapping("/api/auth")
public class LoginController {

    private final AuthService authService;

    public LoginController(AuthService authService) {
        this.authService = authService;
    }

    /**
     * 用户名密码登录
     */
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<LoginResponse>> login(@RequestBody LoginRequest request) {
        try {
            LoginResponse response = authService.login(request.getUsername(), request.getPassword());
            return ResponseEntity.ok(ApiResponse.success(response, "登录成功"));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ApiResponse.error(401, e.getMessage()));
        }
    }

    /**
     * 登出
     */
    @PostMapping("/logout")
    public ResponseEntity<ApiResponse<Void>> logout(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null) {
            authService.logout(authHeader);
        }
        return ResponseEntity.ok(ApiResponse.success(null, "登出成功"));
    }

    /**
     * 验证Token
     */
    @GetMapping("/verify")
    public ResponseEntity<ApiResponse<AuthService.TokenInfo>> verifyToken(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        AuthService.TokenInfo tokenInfo = authService.validateToken(authHeader);
        if (tokenInfo != null) {
            return ResponseEntity.ok(ApiResponse.success(tokenInfo));
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ApiResponse.error(401, "Token无效或已过期"));
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    public ResponseEntity<ApiResponse<AuthService.UserInfo>> getCurrentUser(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        AuthService.TokenInfo tokenInfo = authService.validateToken(authHeader);
        if (tokenInfo == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ApiResponse.error(401, "未登录或Token已过期"));
        }

        AuthService.UserInfo user = authService.getUserById(tokenInfo.userId);
        if (user == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ApiResponse.error(404, "用户不存在"));
        }
        return ResponseEntity.ok(ApiResponse.success(user));
    }
}
