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 { MerchantFinanceService } from './finance.service';
import { MerchantProfileService } from '../profile/profile.service';
import { QueryTransactionDto } from './dto/finance.dto';

@ApiTags('商家财务管理')
@Controller('merchant/finance')
@UseGuards(SellerJwtAuthGuard)
@ApiBearerAuth()
export class MerchantFinanceController {
  constructor(
    private readonly financeService: MerchantFinanceService,
    private readonly profileService: MerchantProfileService,
  ) {}

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

  @Get('account')
  @ApiOperation({ summary: '获取商家账户信息' })
  async getAccount(@CurrentSeller('sub') sellerId: number) {
    const merchantId = await this.getMerchantId(sellerId);
    const account = await this.financeService.getMerchantAccount(merchantId);
    if (!account) throw new NotFoundException('账户不存在');
    return account;
  }

  @Get('wallet')
  @ApiOperation({ summary: '获取商家钱包信息' })
  async getWallet(@CurrentSeller('sub') sellerId: number) {
    return this.getAccount(sellerId);
  }

  @Get('transactions')
  @ApiOperation({ summary: '交易流水列表' })
  async getTransactions(
    @CurrentSeller('sub') sellerId: number,
    @Query() dto: QueryTransactionDto,
  ) {
    const merchantId = await this.getMerchantId(sellerId);
    const account = await this.financeService.getMerchantAccount(merchantId);
    if (!account) throw new NotFoundException('账户不存在');

    return this.financeService.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.financeService.getMerchantAccount(merchantId);
    if (!account) throw new NotFoundException('账户不存在');

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

    const totalExpense = await this.financeService.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,
    };
  }
}
