import {
  Controller,
  Get,
  Post,
  Param,
  Query,
  HttpCode,
  HttpStatus,
  UseGuards,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { SmsService } from '../../../application/services/sms.service';
import { Inject } from '@nestjs/common';
import {
  SMS_LOG_REPOSITORY,
  ISmsLogRepository,
} from '../../../domain/repositories/sms-log.repository.interface';
import {
  SMS_VERIFICATION_REPOSITORY,
  ISmsVerificationRepository,
} from '../../../domain/repositories/sms-verification.repository.interface';
import {
  USER_REPOSITORY,
  IUserRepository,
} from '../../../domain/repositories/user.repository.interface';

@ApiTags('Admin - SMS')
@ApiBearerAuth()
@UseGuards(AuthGuard('jwt'))
@Controller('admin/sms')
export class AdminSmsController {
  constructor(
    @Inject(SMS_LOG_REPOSITORY)
    private readonly smsLogRepo: ISmsLogRepository,
    @Inject(SMS_VERIFICATION_REPOSITORY)
    private readonly smsVerificationRepo: ISmsVerificationRepository,
    @Inject(USER_REPOSITORY)
    private readonly userRepo: IUserRepository,
  ) {}

  /* ── SMS 发送日志 ── */

  @Get('logs')
  @ApiOperation({ summary: '查询 SMS 发送日志' })
  @ApiQuery({ name: 'phone', required: false })
  @ApiQuery({ name: 'limit', required: false })
  @ApiQuery({ name: 'offset', required: false })
  @ApiResponse({ status: 200, description: 'SMS 日志列表' })
  async getSmsLogs(
    @Query('phone') phone?: string,
    @Query('limit') limit = 20,
    @Query('offset') offset = 0,
  ) {
    const logs = phone
      ? await this.smsLogRepo.findByPhone(phone, { limit: +limit, offset: +offset })
      : [];
    // Mask phone in response: 138****8000
    const masked = logs.map((log) => ({
      ...log,
      phone: this.maskPhone(log.phone),
    }));
    return {
      code: 0,
      data: { items: masked, total: masked.length },
      message: 'ok',
    };
  }

  /* ── 用户 SMS 日志 ── */

  @Get('logs/user/:userId')
  @ApiOperation({ summary: '查询指定用户的 SMS 日志' })
  @ApiResponse({ status: 200, description: '用户 SMS 日志列表' })
  async getUserSmsLogs(
    @Param('userId') userId: string,
    @Query('limit') limit = 20,
    @Query('offset') offset = 0,
  ) {
    // 获取用户手机号
    const user = await this.userRepo.findById(userId);
    if (!user || !user.phone) {
      return { code: 0, data: { items: [], total: 0 }, message: 'ok' };
    }
    const logs = await this.smsLogRepo.findByPhone(user.phone, {
      limit: +limit,
      offset: +offset,
    });
    const masked = logs.map((log) => ({
      ...log,
      phone: this.maskPhone(log.phone),
    }));
    return {
      code: 0,
      data: { items: masked, total: masked.length },
      message: 'ok',
    };
  }

  /* ── 账号解锁 ── */

  @Post('unlock/:userId')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '手动解锁用户账号 (清除登录失败计数和锁定时间)' })
  @ApiResponse({ status: 200, description: '解锁成功' })
  async unlockUser(@Param('userId') userId: string) {
    const user = await this.userRepo.findById(userId);
    if (!user) {
      return { code: 1, data: null, message: '用户不存在' };
    }
    user.loginFailCount = 0;
    user.lockedUntil = null;
    await this.userRepo.save(user);
    return {
      code: 0,
      data: null,
      message: '账号已解锁',
    };
  }

  /* ── Private helpers ── */

  private maskPhone(phone: string): string {
    if (!phone) return '';
    // +8613812345678 → +86 138****5678
    const raw = phone.startsWith('+86') ? phone.slice(3) : phone;
    if (raw.length < 7) return phone;
    return (phone.startsWith('+86') ? '+86 ' : '') +
      raw.slice(0, 3) + '****' + raw.slice(-4);
  }
}
