import {
  Controller,
  Post,
  Body,
  UnauthorizedException,
  Logger,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from '@/infrastructure/persistence/prisma/prisma.service';
import { UserApplicationService } from '@/application/services/user-application.service';
import { Public } from '@/shared/guards/jwt-auth.guard';
import { AutoLoginCommand } from '@/application/commands';
import { AutoLoginDto, AdminLoginDto, AdminLoginResponseDto } from '@/api/dto';
import * as bcrypt from 'bcrypt';

@ApiTags('Auth')
@Controller('auth')
export class AuthController {
  private readonly logger = new Logger(AuthController.name);

  constructor(
    private readonly userService: UserApplicationService,
    private readonly jwtService: JwtService,
    private readonly prisma: PrismaService,
  ) {}

  @Public()
  @Post('refresh')
  @ApiOperation({ summary: 'Token刷新' })
  async refresh(@Body() dto: AutoLoginDto) {
    return this.userService.autoLogin(
      new AutoLoginCommand(dto.refreshToken, dto.deviceId),
    );
  }

  @Public()
  @Post('login')
  @ApiOperation({ summary: '管理员登录 (邮箱+密码)' })
  @ApiResponse({ status: 200, type: AdminLoginResponseDto })
  @ApiResponse({ status: 401, description: '邮箱或密码错误' })
  async adminLogin(@Body() dto: AdminLoginDto): Promise<AdminLoginResponseDto> {
    this.logger.log(`[AdminLogin] 尝试登录: ${dto.email}`);

    // 从数据库查找管理员
    const admin = await this.prisma.adminAccount.findUnique({
      where: { email: dto.email },
    });

    if (!admin) {
      this.logger.warn(`[AdminLogin] 管理员不存在: ${dto.email}`);
      throw new UnauthorizedException('邮箱或密码错误');
    }

    // 检查账户状态
    if (admin.status !== 'ACTIVE') {
      this.logger.warn(
        `[AdminLogin] 账户状态异常: ${dto.email}, status=${admin.status}`,
      );
      throw new UnauthorizedException('账户已被禁用');
    }

    // 验证密码 (使用 bcrypt)
    const isPasswordValid = await bcrypt.compare(
      dto.password,
      admin.passwordHash,
    );

    if (!isPasswordValid) {
      this.logger.warn(`[AdminLogin] 密码错误: ${dto.email}`);
      throw new UnauthorizedException('邮箱或密码错误');
    }

    // 更新最后登录时间
    await this.prisma.adminAccount.update({
      where: { id: admin.id },
      data: { lastLoginAt: new Date() },
    });

    // 生成 JWT Token
    const payload = {
      sub: admin.id.toString(),
      email: admin.email,
      role: admin.role,
      type: 'admin',
    };

    const accessToken = this.jwtService.sign(payload, { expiresIn: '24h' });
    const refreshToken = this.jwtService.sign(payload, { expiresIn: '7d' });

    this.logger.log(`[AdminLogin] 登录成功: ${dto.email}`);

    return {
      userId: admin.id.toString(),
      email: admin.email,
      nickname: admin.nickname,
      role: admin.role,
      accessToken,
      refreshToken,
    };
  }
}
