import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth } from '@nestjs/swagger';
import { Controller, Post, Body, Get, HttpCode, HttpStatus, Req, Res, UseGuards } from '@nestjs/common';
import { AdminAuthService } from './admin-auth.service';
import { AdminLoginDto, AdminRefreshDto } from './dto';
import { AdminPublic } from '../../common/decorators/admin-public.decorator';
import { AdminAuthGuard } from '../../common/guards/admin-auth.guard';
import { AdminRolesGuard } from '../../common/guards/admin-roles.guard';
import { AdminLoginRateLimit } from '../../common/decorators/rate-limit.decorator';
import type { Request, Response } from 'express';

const ACCESS_COOKIE = {
  httpOnly: true,
  secure: true,
  sameSite: 'strict' as const,
  path: '/admin-api',
  maxAge: 60 * 60 * 1000, // 1 小时
} as const;

const REFRESH_COOKIE = {
  httpOnly: true,
  secure: true,
  sameSite: 'strict' as const,
  path: '/admin-api/auth',
  maxAge: 7 * 24 * 60 * 60 * 1000, // 7 天
} as const;

@ApiTags('admin-auth')
@Controller('admin-api/auth')
@UseGuards(AdminAuthGuard, AdminRolesGuard)
export class AdminAuthController {
  constructor(private readonly adminAuthService: AdminAuthService) {}

  @AdminPublic()
  @Post('login')
  @HttpCode(HttpStatus.OK)
  @AdminLoginRateLimit()
  @ApiOperation({ summary: '管理员登录' })
  @ApiResponse({ status: 200, description: '登录成功' })
  @ApiResponse({ status: 401, description: '邮箱或密码错误' })
  @ApiResponse({ status: 403, description: '账号已禁用或锁定' })
  async login(@Body() dto: AdminLoginDto, @Req() req: Request, @Res({ passthrough: true }) res: Response) {
    const ip = (req.ip || '').replace('::ffff:', '');
    const result = await this.adminAuthService.login(dto.email, dto.password, ip, req.headers['user-agent']);

    res.cookie('admin_access_token', result.accessToken, ACCESS_COOKIE);
    res.cookie('admin_refresh_token', result.refreshToken, REFRESH_COOKIE);

    return result;
  }

  @AdminPublic()
  @Post('refresh')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '刷新管理员令牌' })
  @ApiResponse({ status: 200, description: '刷新成功' })
  @ApiResponse({ status: 401, description: '刷新令牌无效' })
  async refresh(@Body() dto: AdminRefreshDto, @Req() req: Request, @Res({ passthrough: true }) res: Response) {
    const refreshIp = (req.ip || '').replace('::ffff:', '');
    // 支持 body（旧客户端）或 cookie（新前端）
    const token = dto.refreshToken || req.cookies?.admin_refresh_token;
    const result = await this.adminAuthService.refresh(token, refreshIp, req.headers['user-agent']);

    res.cookie('admin_access_token', result.accessToken, ACCESS_COOKIE);
    res.cookie('admin_refresh_token', result.refreshToken, REFRESH_COOKIE);

    return result;
  }

  @Post('logout')
  @HttpCode(HttpStatus.OK)
  @ApiBearerAuth()
  @ApiOperation({ summary: '管理员退出登录' })
  @ApiResponse({ status: 200, description: '退出成功' })
  async logout(@Req() req: Request, @Body() dto: AdminRefreshDto, @Res({ passthrough: true }) res: Response) {
    const adminUser = (req as any).adminUser;
    // 支持 body（旧客户端）或 cookie（新前端）
    const token = dto.refreshToken || req.cookies?.admin_refresh_token;
    if (token) {
      await this.adminAuthService.logout(adminUser.id, token);
    }

    res.clearCookie('admin_access_token', { path: '/admin-api' });
    res.clearCookie('admin_refresh_token', { path: '/admin-api/auth' });

    return { success: true, message: '已退出登录' };
  }

  @Get('me')
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取当前管理员信息' })
  @ApiResponse({ status: 200, description: '成功' })
  async getMe(@Req() req: Request) {
    const adminUser = (req as any).adminUser;
    return this.adminAuthService.getMe(adminUser.id);
  }
}
