package com.lesingle.creation.controller;

import com.lesingle.creation.common.core.Result;
import com.lesingle.creation.common.security.UserPrincipal;
import com.lesingle.creation.dto.auth.LoginDTO;
import com.lesingle.creation.service.AuthService;
import com.lesingle.creation.vo.auth.LoginResponseVO;
import com.lesingle.creation.vo.auth.UserInfoVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 */
@Slf4j
@Tag(name = "认证管理", description = "用户登录、登出、刷新 Token 等接口")
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;

    /**
     * 用户登录
     */
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<LoginResponseVO> login(@RequestBody LoginDTO loginDTO) {
        LoginResponseVO response = authService.login(loginDTO);
        return Result.success(response);
    }

    /**
     * 获取当前用户信息
     */
    @Operation(summary = "获取当前用户信息")
    @GetMapping("/me")
    public Result<UserInfoVO> getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        log.debug("Authentication: {}", authentication);
        if (authentication == null || !authentication.isAuthenticated()) {
            return Result.fail(401, "未授权");
        }

        Object principal = authentication.getPrincipal();
        log.debug("Principal type: {}", principal != null ? principal.getClass().getName() : "null");
        Long userId;

        if (principal instanceof UserPrincipal) {
            userId = ((UserPrincipal) principal).getUserId();
            log.info("UserPrincipal userId: {}", userId);
        } else if (principal instanceof UserDetails) {
            // 从 UserDetails 获取用户名，然后通过用户名查询用户
            String username = ((UserDetails) principal).getUsername();
            log.debug("Principal 是 UserDetails 类型，用户名：{}", username);
            // 尝试从 authorities 获取用户 ID（如果有）
            userId = null;
        } else {
            log.warn("无法识别的 Principal 类型：{}", principal != null ? principal.getClass().getName() : "null");
            return Result.fail(401, "无法获取用户信息");
        }

        if (userId == null) {
            return Result.fail(401, "无法获取用户 ID");
        }

        UserInfoVO userInfo = authService.getUserInfo(userId);
        return Result.success(userInfo);
    }

    /**
     * 用户登出
     */
    @Operation(summary = "用户登出")
    @PostMapping("/logout")
    public Result<Void> logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            String username = ((UserDetails) authentication.getPrincipal()).getUsername();
            log.info("用户登出：{}", username);
        }
        // TODO: 可以将 token 加入黑名单（使用 Redis）
        return Result.success(null);
    }

    /**
     * 刷新 Token
     */
    @Operation(summary = "刷新 Token")
    @PostMapping("/refresh-token")
    public Result<LoginResponseVO> refreshToken(@RequestHeader("Authorization") String token) {
        LoginResponseVO response = authService.refreshToken(token);
        return Result.success(response);
    }
}
