import {
  Injectable,
  NotFoundException,
  BadRequestException,
  Logger,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Merchant } from '@/entities/merchant.entity';
import { MerchantAccount } from '@/entities/merchant-account.entity';
import { Room } from '@/entities/room.entity';
import { RoomCalendar } from '@/entities/room-calendar.entity';
import {
  ApplyMerchantDto,
  UpdateMerchantDto,
} from './dto/profile.dto';

@Injectable()
export class MerchantProfileService {
  private readonly logger = new Logger(MerchantProfileService.name);

  constructor(
    @InjectRepository(Merchant)
    private merchantRepo: Repository<Merchant>,
    @InjectRepository(MerchantAccount)
    private merchantAccountRepo: Repository<MerchantAccount>,
    @InjectRepository(Room)
    private roomRepo: Repository<Room>,
    @InjectRepository(RoomCalendar)
    private roomCalendarRepo: Repository<RoomCalendar>,
  ) {}

  async apply(sellerId: number, dto: ApplyMerchantDto) {
    const existing = await this.merchantRepo.findOne({ where: { sellerId } });
    if (existing) {
      throw new BadRequestException('您已提交过商家申请');
    }

    const merchant = this.merchantRepo.create({ sellerId, ...dto });
    return this.merchantRepo.save(merchant);
  }

  async findBySellerId(sellerId: number) {
    return this.merchantRepo.findOne({ where: { sellerId } });
  }

  async findById(id: number) {
    const merchant = await this.merchantRepo.findOne({ where: { id } });
    if (!merchant) throw new NotFoundException('商家不存在');
    return merchant;
  }

  async update(id: number, dto: UpdateMerchantDto) {
    const merchant = await this.findById(id);
    // 审核通过或审核拒绝后修改信息，需要重新进入审核
    if (merchant.status === 'approved' || merchant.status === 'rejected') {
      await this.merchantRepo.update(id, {
        ...dto,
        status: 'pending',
        rejectReason: '',
      });
    } else {
      await this.merchantRepo.update(id, dto);
    }
    return this.findById(id);
  }

  private async createMerchantAccount(merchantId: number): Promise<void> {
    try {
      const existingAccount = await this.merchantAccountRepo.findOne({
        where: { merchant_id: merchantId },
      });

      if (!existingAccount) {
        const account = this.merchantAccountRepo.create({
          merchant_id: merchantId,
          balance: 0,
          frozen_balance: 0,
          debt_amount: 0,
          total_income: 0,
          total_expense: 0,
          total_settlement: 0,
          total_withdraw: 0,
          pending_settlement: 0,
          status: 'active',
        });
        await this.merchantAccountRepo.save(account);
        this.logger.log(`商家账户创建成功: merchantId=${merchantId}`);
      }
    } catch (error) {
      this.logger.error(`创建商家账户失败: merchantId=${merchantId}`, error);
    }
  }
}
