import {
  Controller, Get, Post, Param, Query, Req, UseGuards, ParseUUIDPipe,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { JwtAuthGuard, Roles, RolesGuard, UserRole } from '@genex/common';
import { AdminRiskService } from '../../../application/services/admin-risk.service';
import { Request } from 'express';
import { ListRiskAlertsQueryDto } from '../dto/admin-risk.dto';
import { PaginationQueryDto } from '../dto/pagination.dto';

@ApiTags('Admin - Risk Center')
@Controller('admin/risk')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.ADMIN)
@ApiBearerAuth()
export class AdminRiskController {
  constructor(private readonly adminRiskService: AdminRiskService) {}

  @Get('dashboard')
  @ApiOperation({ summary: 'Risk dashboard stats (active alerts, suspicious trades, frozen accounts)' })
  async getDashboard() {
    const data = await this.adminRiskService.getDashboard();
    return { code: 0, data };
  }

  @Get('alerts')
  @ApiOperation({ summary: 'List active risk/AML alerts (paginated)' })
  async listAlerts(@Query() query: ListRiskAlertsQueryDto) {
    const data = await this.adminRiskService.listAlerts(
      query.page,
      query.limit,
      query.status,
      query.pattern,
    );
    return { code: 0, data };
  }

  @Get('suspicious-trades')
  @ApiOperation({ summary: 'List flagged suspicious transactions' })
  async listSuspiciousTrades(@Query() query: PaginationQueryDto) {
    const data = await this.adminRiskService.listSuspiciousTrades(query.page, query.limit);
    return { code: 0, data };
  }

  @Get('blacklist')
  @ApiOperation({ summary: 'List blacklisted users (OFAC matches)' })
  async listBlacklist(@Query() query: PaginationQueryDto) {
    const data = await this.adminRiskService.listBlacklist(query.page, query.limit);
    return { code: 0, data };
  }

  @Post('suspicious/:id/freeze')
  @ApiOperation({ summary: 'Freeze account associated with suspicious alert' })
  async freezeAccount(
    @Param('id', ParseUUIDPipe) id: string,
    @Req() req: Request,
  ) {
    const user = req.user as any;
    const ip = req.ip || req.headers['x-forwarded-for'] as string;
    const data = await this.adminRiskService.freezeAccount(
      id,
      user.sub,
      user.email || user.phone || 'admin',
      ip,
    );
    return { code: 0, data, message: 'Account frozen successfully' };
  }

  @Post('suspicious/:id/sar')
  @ApiOperation({ summary: 'Generate SAR from suspicious alert' })
  async generateSar(
    @Param('id', ParseUUIDPipe) id: string,
    @Req() req: Request,
  ) {
    const user = req.user as any;
    const ip = req.ip || req.headers['x-forwarded-for'] as string;
    const data = await this.adminRiskService.generateSar(
      id,
      user.sub,
      user.email || user.phone || 'admin',
      ip,
    );
    return { code: 0, data, message: 'SAR generated successfully' };
  }
}
