import {
  Controller, Get, Post, Param, Query, Body, Req, UseGuards, ParseUUIDPipe,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { JwtAuthGuard, Roles, RolesGuard, UserRole } from '@genex/common';
import { AdminInsuranceService } from '../../../application/services/admin-insurance.service';
import { Request } from 'express';
import { ListClaimsQueryDto, RejectClaimDto } from '../dto/admin-insurance.dto';

@ApiTags('Admin - Insurance & Consumer Protection')
@Controller('admin/insurance')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.ADMIN)
@ApiBearerAuth()
export class AdminInsuranceController {
  constructor(private readonly adminInsuranceService: AdminInsuranceService) {}

  @Get('stats')
  @ApiOperation({ summary: 'Get protection fund statistics' })
  async getStats() {
    const data = await this.adminInsuranceService.getStats();
    return { code: 0, data };
  }

  @Get('claims')
  @ApiOperation({ summary: 'List insurance claims (paginated)' })
  async listClaims(@Query() query: ListClaimsQueryDto) {
    const data = await this.adminInsuranceService.listClaims(
      query.page,
      query.limit,
      query.status,
    );
    return { code: 0, data };
  }

  @Post('claims/:id/approve')
  @ApiOperation({ summary: 'Approve an insurance claim' })
  async approveClaim(
    @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.adminInsuranceService.approveClaim(
      id,
      user.sub,
      user.email || user.phone || 'admin',
      ip,
    );
    return { code: 0, data, message: 'Claim approved' };
  }

  @Post('claims/:id/reject')
  @ApiOperation({ summary: 'Reject an insurance claim' })
  async rejectClaim(
    @Param('id', ParseUUIDPipe) id: string,
    @Body() body: RejectClaimDto,
    @Req() req: Request,
  ) {
    const user = req.user as any;
    const ip = req.ip || req.headers['x-forwarded-for'] as string;
    const data = await this.adminInsuranceService.rejectClaim(
      id,
      body,
      user.sub,
      user.email || user.phone || 'admin',
      ip,
    );
    return { code: 0, data, message: 'Claim rejected' };
  }
}
