package com.emotion.controller;

import com.emotion.common.Result;
import com.emotion.dto.request.AdminLoginRequest;
import com.emotion.dto.request.RefreshTokenRequest;
import com.emotion.dto.response.AdminAuthResponse;
import com.emotion.dto.response.AdminInfoResponse;
import com.emotion.service.AdminAuthService;
import com.emotion.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 管理员认证控制器
 *
 * @author emotion-museum
 * @date 2025-10-27
 */
@RestController
@RequestMapping("/admin/auth")
@Tag(name = "管理员认证管理", description = "管理员登录、登出等认证相关接口")
public class AdminAuthController {

    @Autowired
    private AdminAuthService adminAuthService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    @Operation(summary = "管理员登录", description = "使用账号和密码登录")
    public Result<AdminAuthResponse> login(@Validated @RequestBody AdminLoginRequest request) {
        AdminAuthResponse response = adminAuthService.login(request);
        return Result.success("登录成功", response);
    }

    /**
     * 获取当前管理员信息
     */
    @GetMapping("/info")
    @Operation(summary = "获取当前管理员信息", description = "根据Token获取当前登录的管理员信息")
    public Result<AdminInfoResponse> getCurrentAdminInfo(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return Result.unauthorized("未登录");
        }
        
        String token = authHeader.substring(7);
        String adminId = jwtUtil.getUserIdFromToken(token);
        
        AdminInfoResponse adminInfo = adminAuthService.getCurrentAdminInfo(adminId);
        return Result.success(adminInfo);
    }

    /**
     * 管理员登出
     */
    @PostMapping("/logout")
    @Operation(summary = "管理员登出", description = "退出登录")
    public Result<Void> logout(HttpServletRequest request) {
        adminAuthService.logout(request);
        return Result.success("登出成功", null);
    }

    /**
     * 刷新访问令牌
     */
    @PostMapping("/refreshToken")
    @Operation(summary = "刷新访问令牌", description = "使用刷新令牌获取新的访问令牌")
    public Result<AdminAuthResponse> refreshToken(@Validated @RequestBody RefreshTokenRequest request) {
        AdminAuthResponse response = adminAuthService.refreshToken(request.getRefreshToken());
        return Result.success("令牌刷新成功", response);
    }

    /**
     * 验证访问令牌
     */
    @GetMapping("/validateToken")
    @Operation(summary = "验证访问令牌", description = "验证当前Token是否有效")
    public Result<Boolean> validateToken(HttpServletRequest request) {
        boolean isValid = adminAuthService.validateToken(request);
        return Result.success(isValid);
    }
}
