import {
  Controller,
  Get,
  Param,
  Query,
  UseGuards,
  NotFoundException,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { SettlementService } from '@/modules/shared/finance/settlement.service';
import { SellerJwtAuthGuard } from '@/common/guards/seller-jwt-auth.guard';
import { CurrentSeller } from '@/common/decorators/current-seller.decorator';
import { MerchantService } from '@/modules/merchant/merchant.service';
import { QuerySettlementDto } from '@/modules/shared/finance/dto/settlement.dto';

@ApiTags('结算管理(商家)')
@Controller('merchant/finance/settlements')
@UseGuards(SellerJwtAuthGuard)
@ApiBearerAuth()
export class SettlementMerchantController {
  constructor(
    private readonly settlementService: SettlementService,
    private readonly merchantService: MerchantService,
  ) {}

  private async getMerchantId(sellerId: number): Promise<number> {
    const merchant = await this.merchantService.findBySellerId(sellerId);
    if (!merchant) throw new NotFoundException('店铺不存在');
    return merchant.id;
  }

  @Get()
  @ApiOperation({ summary: '商家查询结算记录' })
  async getSettlements(
    @CurrentSeller('sub') sellerId: number,
    @Query() dto: QuerySettlementDto,
  ) {
    const merchantId = await this.getMerchantId(sellerId);
    return this.settlementService.getSettlements({
      merchantId,
      status: dto.status,
      startDate: dto.startDate,
      endDate: dto.endDate,
      page: dto.page,
      pageSize: dto.pageSize,
    });
  }

  @Get(':id')
  @ApiOperation({ summary: '商家查询结算详情' })
  async getSettlementDetail(
    @CurrentSeller('sub') sellerId: number,
    @Param('id') id: number,
  ) {
    const merchantId = await this.getMerchantId(sellerId);
    const settlement = await this.settlementService.getSettlementDetail(id);

    // 验证结算单属于当前商家
    if (settlement.merchantId !== merchantId) {
      throw new NotFoundException('结算单不存在');
    }

    return settlement;
  }

  @Get(':id/items')
  @ApiOperation({ summary: '查询结算明细' })
  async getSettlementItems(
    @CurrentSeller('sub') sellerId: number,
    @Param('id') id: number,
    @Query('page') page: number = 1,
    @Query('pageSize') pageSize: number = 10,
  ) {
    const merchantId = await this.getMerchantId(sellerId);
    const settlement = await this.settlementService.getSettlementDetail(id);

    // 验证结算单属于当前商家
    if (settlement.merchantId !== merchantId) {
      throw new NotFoundException('结算单不存在');
    }

    // 分页处理
    const items = settlement.items || [];
    const total = items.length;
    const start = (page - 1) * pageSize;
    const end = start + pageSize;
    const paginatedItems = items.slice(start, end);

    return {
      items: paginatedItems,
      total,
      page,
      pageSize
    };
  }
}
