import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Room } from '@/entities/room.entity';
import { QueryRoomDto } from './dto/room.dto';

@Injectable()
export class AdminRoomService {
  constructor(
    @InjectRepository(Room)
    private roomRepo: Repository<Room>,
  ) {}

  async findAllForAdmin(query: QueryRoomDto) {
    const { page = 1, pageSize = 10, auditStatus, keyword } = query;
    const qb = this.roomRepo.createQueryBuilder('room')
      .leftJoinAndSelect('room.merchant', 'merchant');

    if (auditStatus) {
      qb.andWhere('room.auditStatus = :auditStatus', { auditStatus });
    }

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

    qb.orderBy('room.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 room = await this.roomRepo.findOne({ where: { id } });
    if (!room) throw new NotFoundException('房源不存在');

    await this.roomRepo.update(id, {
      auditStatus: 'approved',
      auditRejectReason: undefined,
    });
    return { message: '审核通过' };
  }

  async reject(id: number, reason: string) {
    const room = await this.roomRepo.findOne({ where: { id } });
    if (!room) throw new NotFoundException('房源不存在');

    await this.roomRepo.update(id, {
      auditStatus: 'rejected',
      auditRejectReason: reason,
    });
    return { message: '审核拒绝' };
  }
}
