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 { AdminDisputeService } from '../../../application/services/admin-dispute.service';
import { Request } from 'express';
import {
  ListDisputesQueryDto,
  ResolveDisputeDto,
  ArbitrateDisputeDto,
} from '../dto/admin-dispute.dto';

@ApiTags('Admin - Dispute Management')
@Controller('admin/disputes')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.ADMIN)
@ApiBearerAuth()
export class AdminDisputeController {
  constructor(private readonly adminDisputeService: AdminDisputeService) {}

  @Get()
  @ApiOperation({ summary: 'List disputes (paginated, filter by status/type)' })
  async listDisputes(@Query() query: ListDisputesQueryDto) {
    const data = await this.adminDisputeService.listDisputes(
      query.page,
      query.limit,
      query.status,
      query.type,
    );
    return { code: 0, data };
  }

  @Get(':id')
  @ApiOperation({ summary: 'Get dispute detail' })
  async getDisputeDetail(@Param('id', ParseUUIDPipe) id: string) {
    const data = await this.adminDisputeService.getDisputeDetail(id);
    return { code: 0, data };
  }

  @Post(':id/resolve')
  @ApiOperation({ summary: 'Resolve dispute with decision' })
  async resolveDispute(
    @Param('id', ParseUUIDPipe) id: string,
    @Body() body: ResolveDisputeDto,
    @Req() req: Request,
  ) {
    const user = req.user as any;
    const ip = req.ip || req.headers['x-forwarded-for'] as string;
    const data = await this.adminDisputeService.resolveDispute(
      id,
      body,
      user.sub,
      user.email || user.phone || 'admin',
      ip,
    );
    return { code: 0, data, message: 'Dispute resolved' };
  }

  @Post(':id/arbitrate')
  @ApiOperation({ summary: 'Arbitration action on dispute' })
  async arbitrate(
    @Param('id', ParseUUIDPipe) id: string,
    @Body() body: ArbitrateDisputeDto,
    @Req() req: Request,
  ) {
    const user = req.user as any;
    const ip = req.ip || req.headers['x-forwarded-for'] as string;
    const data = await this.adminDisputeService.arbitrate(
      id,
      body,
      user.sub,
      user.email || user.phone || 'admin',
      ip,
    );
    return { code: 0, data, message: 'Arbitration recorded' };
  }
}
