import {
  Controller,
  Post,
  Get,
  Param,
  Body,
  Query,
  UseGuards,
  Request,
  NotFoundException,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { JwtAuthGuard } from '../guards/jwt-auth.guard';
import { TransferApplicationService } from '../../application/services/transfer-application.service';
import { CreateTransferDto } from '../dto/request/create-transfer.dto';
import { QueryTransfersDto } from '../dto/request/query-transfers.dto';
import { TransferOrderResponse } from '../dto/response/transfer-order.response';

@ApiTags('转让订单')
@ApiBearerAuth()
@Controller('transfers')
@UseGuards(JwtAuthGuard)
export class TransferController {
  constructor(
    private readonly transferService: TransferApplicationService,
  ) {}

  @Post()
  @ApiOperation({ summary: '发起转让（买方向卖方购买）' })
  async createTransfer(
    @Body() dto: CreateTransferDto,
    @Request() req: any,
  ): Promise<{ transferOrderNo: string }> {
    return this.transferService.createTransferOrder({
      buyerUserId: BigInt(req.user.id),
      buyerAccountSequence: req.user.accountSequence,
      sourceOrderNo: dto.sourceOrderNo,
      treeCount: dto.treeCount,
      transferPrice: dto.transferPrice,
    });
  }

  @Post(':transferOrderNo/seller-confirm')
  @ApiOperation({ summary: '卖方确认转让' })
  async sellerConfirm(
    @Param('transferOrderNo') transferOrderNo: string,
    @Request() req: any,
  ): Promise<{ success: boolean }> {
    await this.transferService.sellerConfirm(
      transferOrderNo,
      BigInt(req.user.id),
    );
    return { success: true };
  }

  @Post(':transferOrderNo/cancel')
  @ApiOperation({ summary: '取消转让' })
  async cancelTransfer(
    @Param('transferOrderNo') transferOrderNo: string,
    @Request() req: any,
  ): Promise<{ success: boolean }> {
    await this.transferService.cancelTransfer(
      transferOrderNo,
      BigInt(req.user.id),
    );
    return { success: true };
  }

  @Get()
  @ApiOperation({ summary: '查询我的转让记录' })
  async getMyTransfers(
    @Query() query: QueryTransfersDto,
    @Request() req: any,
  ): Promise<TransferOrderResponse[]> {
    const orders = await this.transferService.getMyTransfers(
      BigInt(req.user.id),
      query.role || 'all',
      { limit: query.limit, offset: query.offset },
    );
    return orders.map(TransferOrderResponse.fromDomain);
  }

  @Get(':transferOrderNo')
  @ApiOperation({ summary: '查询转让详情' })
  async getTransferOrder(
    @Param('transferOrderNo') transferOrderNo: string,
  ): Promise<TransferOrderResponse> {
    const order = await this.transferService.getTransferOrder(transferOrderNo);
    if (!order) {
      throw new NotFoundException(`转让订单 ${transferOrderNo} 不存在`);
    }
    return TransferOrderResponse.fromDomain(order);
  }
}
