import { Controller, Get, Post, Body, Query, UseGuards, Logger } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { FraudService, FraudRuleConfig } from './fraud.service';
import { IamGuard, IamRoles } from '../../common/iam-adapter';
import { UserRole } from '@prisma/client';

@ApiTags('Fraud Detection')
@Controller('fraud')
@UseGuards(IamGuard)
@ApiBearerAuth('IAM-auth')
export class FraudController {
  private readonly logger = new Logger(FraudController.name);

  constructor(private fraudService: FraudService) {}

  /**
   * Get fraud alerts
   */
  @Get('alerts')
  @IamRoles('ADMIN', 'SUPERVISOR')
  @ApiOperation({ summary: 'Get fraud alerts' })
  async getAlerts(
    @Query('userId') userId?: string,
    @Query('limit') limit?: string,
    @Query('offset') offset?: string,
  ) {
    const alerts = await this.fraudService.getAlerts(userId, parseInt(limit || '100'), parseInt(offset || '0'));
    return { data: alerts, total: alerts.length };
  }

  /**
   * Get fraud rules
   */
  @Get('rules')
  @IamRoles('ADMIN')
  @ApiOperation({ summary: 'Get fraud detection rules' })
  async getRules() {
    const rules = await this.fraudService.getRules();
    return { data: rules };
  }

  /**
   * Create or update fraud rule
   */
  @Post('rules')
  @IamRoles('ADMIN')
  @ApiOperation({ summary: 'Create or update fraud rule' })
  async upsertRule(@Body() body: { type: string; config: FraudRuleConfig }) {
    const rule = await this.fraudService.upsertRule(body.type, body.config);
    return { data: rule, message: 'Rule updated successfully' };
  }

  /**
   * Block user temporarily
   */
  @Post('actions/block')
  @IamRoles('ADMIN', 'SUPERVISOR')
  @ApiOperation({ summary: 'Block user temporarily' })
  async blockUser(@Body() body: { userId: string; durationMinutes: number }) {
    await this.fraudService.blockUserTemporarily(body.userId, body.durationMinutes);
    return { message: `User blocked for ${body.durationMinutes} minutes` };
  }

  /**
   * Unblock user
   */
  @Post('actions/unblock')
  @IamRoles('ADMIN', 'SUPERVISOR')
  @ApiOperation({ summary: 'Unblock user' })
  async unblockUser(@Body() body: { userId: string }) {
    await this.fraudService.unblockUser(body.userId);
    return { message: 'User unblocked' };
  }
}
