import { Controller, Get, Post, Patch, Param, Body, Query, Logger } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { FraudService, FraudRuleConfig } from './fraud.service';
import { PassengerStaff } from '../../common/passenger-guards';
import { PASSENGER_PERMS } from '../../seed/passenger-permissions.registry';

@ApiTags('Fraud Detection')
@Controller('fraud')
@PassengerStaff([PASSENGER_PERMS.fraud.view, PASSENGER_PERMS.admin])
@ApiBearerAuth('IAM-auth')
export class FraudController {
  private readonly logger = new Logger(FraudController.name);

  constructor(private fraudService: FraudService) {}

  /**
   * Get fraud alerts
   */
  @Get('alerts')
  @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')
  @ApiOperation({ summary: 'Get fraud detection rules' })
  async getRules() {
    const rules = await this.fraudService.getRules();
    return { data: rules };
  }

  /**
   * Create or update fraud rule
   */
  @Post('rules')
  @PassengerStaff([PASSENGER_PERMS.fraud.manage, PASSENGER_PERMS.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' };
  }

  /**
   * Acknowledge a fraud alert
   */
  @Patch('alerts/:id/acknowledge')
  @PassengerStaff([PASSENGER_PERMS.fraud.manage, PASSENGER_PERMS.admin])
  @ApiOperation({ summary: 'Acknowledge a fraud alert' })
  async acknowledgeAlert(@Param('id') id: string) {
    const alert = await this.fraudService.acknowledgeAlert(id);
    return { data: alert, message: 'Alert acknowledged' };
  }

  /**
   * Block user via userId
   */
  @Post('users/:userId/block')
  @PassengerStaff([PASSENGER_PERMS.fraud.manage, PASSENGER_PERMS.admin])
  @ApiOperation({ summary: 'Block user by userId' })
  async blockUserById(
    @Param('userId') userId: string,
    @Body() body: { reason?: string; durationMinutes?: number },
  ) {
    await this.fraudService.blockUserTemporarily(userId, body.durationMinutes ?? 60);
    return { message: `User blocked for ${body.durationMinutes ?? 60} minutes` };
  }

  /**
   * Block user temporarily
   */
  @Post('actions/block')
  @PassengerStaff([PASSENGER_PERMS.fraud.manage, PASSENGER_PERMS.admin])
  @ApiOperation({ summary: 'Block user temporarily' })
  async blockUser(@Body() body: { iamUserId: string; durationMinutes: number }) {
    await this.fraudService.blockUserTemporarily(body.iamUserId, body.durationMinutes);
    return { message: `User blocked for ${body.durationMinutes} minutes` };
  }

  /**
   * Unblock user
   */
  @Post('actions/unblock')
  @PassengerStaff([PASSENGER_PERMS.fraud.manage, PASSENGER_PERMS.admin])
  @ApiOperation({ summary: 'Unblock user' })
  async unblockUser(@Body() body: { iamUserId: string }) {
    await this.fraudService.unblockUser(body.iamUserId);
    return { message: 'User unblocked' };
  }
}
