import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Merchant } from '@/entities/merchant.entity';
import { QueryMerchantDto } from './dto/merchant.dto';

@Injectable()
export class AdminMerchantService {
  constructor(
    @InjectRepository(Merchant)
    private merchantRepo: Repository<Merchant>,
  ) {}

  async findAll(query: QueryMerchantDto) {
    const { page = 1, pageSize = 10, status, keyword } = query;
    const qb = this.merchantRepo.createQueryBuilder('merchant');

    if (status) {
      qb.andWhere('merchant.status = :status', { status });
    }

    if (keyword) {
      qb.andWhere('merchant.shopName LIKE :keyword', { keyword: `%${keyword}%` });
    }

    qb.orderBy('merchant.createdAt', 'DESC')
      .skip((page - 1) * pageSize)
      .take(pageSize);

    const [list, total] = await qb.getManyAndCount();

    return {
      list,
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize),
    };
  }

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

    await this.merchantRepo.update(id, {
      status: 'approved',
      rejectReason: '',
    });
    return { message: '审核通过' };
  }

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

    await this.merchantRepo.update(id, {
      status: 'rejected',
      rejectReason: reason,
    });
    return { message: '审核拒绝' };
  }

  async freeze(id: number) {
    await this.merchantRepo.update(id, { status: 'frozen' });
    return { message: '已冻结' };
  }

  async unfreeze(id: number) {
    await this.merchantRepo.update(id, { status: 'approved' });
    return { message: '已解冻' };
  }
}
