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

@ApiTags('交易流水(商家)')
@Controller('merchant/finance/transactions')
@UseGuards(SellerJwtAuthGuard)
@ApiBearerAuth()
export class TransactionSellerController {
  constructor(
    private readonly transactionService: TransactionService,
    private readonly accountService: AccountService,
    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 getTransactions(
    @CurrentSeller('sub') sellerId: number,
    @Query() dto: QueryTransactionDto,
  ) {
    const merchantId = await this.getMerchantId(sellerId);
    const account = await this.accountService.getMerchantAccount(merchantId);

    return this.transactionService.getMerchantTransactions({
      accountId: account.id,
      direction: dto.direction,
      transactionType: dto.transactionType,
      startDate: dto.startDate,
      endDate: dto.endDate,
      page: dto.page,
      pageSize: dto.pageSize,
    });
  }

  @Get('statistics')
  @ApiOperation({ summary: '交易统计' })
  async getStatistics(
    @CurrentSeller('sub') sellerId: number,
    @Query() dto: QueryTransactionDto,
  ) {
    const merchantId = await this.getMerchantId(sellerId);
    const account = await this.accountService.getMerchantAccount(merchantId);

    const totalIncome = await this.transactionService.sumMerchantTransactions({
      accountId: account.id,
      direction: 'income',
      transactionType: dto.transactionType,
      startDate: dto.startDate,
      endDate: dto.endDate,
    });

    const totalExpense = await this.transactionService.sumMerchantTransactions({
      accountId: account.id,
      direction: 'expense',
      transactionType: dto.transactionType,
      startDate: dto.startDate,
      endDate: dto.endDate,
    });

    return {
      total_income: totalIncome,
      total_expense: totalExpense,
      net_amount: totalIncome - totalExpense,
    };
  }
}
