import {
  Controller,
  Get,
  Post,
  Param,
  Query,
  Body,
  UseGuards,
  ParseUUIDPipe,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { AdminIssuerService } from '../../../application/services/admin-issuer.service';
import { RolesGuard, Roles } from '../guards/roles.guard';
import { ListIssuersQueryDto, RejectIssuerDto } from '../dto/issuer.dto';

@ApiTags('Admin - Issuers')
@Controller('admin/issuers')
@UseGuards(AuthGuard('jwt'), RolesGuard)
@Roles('admin')
@ApiBearerAuth()
export class AdminIssuerController {
  constructor(private readonly adminIssuerService: AdminIssuerService) {}

  @Get()
  @ApiOperation({ summary: 'List issuers with filters (admin)' })
  async listIssuers(@Query() query: ListIssuersQueryDto) {
    const result = await this.adminIssuerService.listIssuers({
      page: query.page,
      limit: query.limit,
      status: query.status,
      search: query.search,
    });
    return { code: 0, data: result };
  }

  @Get('ai-pre-review')
  @ApiOperation({ summary: 'AI pre-review recommendation for pending issuers' })
  async getAiPreReview() {
    const result = await this.adminIssuerService.getAiPreReview();
    return { code: 0, data: result };
  }

  @Get(':id')
  @ApiOperation({ summary: 'Get issuer detail with credit rating and documents (admin)' })
  async getIssuerDetail(@Param('id', ParseUUIDPipe) id: string) {
    const result = await this.adminIssuerService.getIssuerDetail(id);
    return { code: 0, data: result };
  }

  @Post(':id/approve')
  @ApiOperation({ summary: 'Approve a pending issuer (admin)' })
  async approveIssuer(@Param('id', ParseUUIDPipe) id: string) {
    const issuer = await this.adminIssuerService.approveIssuer(id);
    return { code: 0, data: issuer, message: 'Issuer approved successfully' };
  }

  @Post(':id/reject')
  @ApiOperation({ summary: 'Reject a pending issuer with reason (admin)' })
  async rejectIssuer(
    @Param('id', ParseUUIDPipe) id: string,
    @Body() dto: RejectIssuerDto,
  ) {
    const issuer = await this.adminIssuerService.rejectIssuer(id, dto.reason);
    return { code: 0, data: issuer, message: 'Issuer rejected' };
  }
}
