import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Review } from '@/entities/review.entity';
import { QueryReviewDto } from './dto/review.dto';

@Injectable()
export class AdminReviewService {
  constructor(
    @InjectRepository(Review)
    private reviewRepo: Repository<Review>,
  ) {}

  async findAllForAdmin(query: QueryReviewDto) {
    const { page = 1, pageSize = 10, status } = query;
    const qb = this.reviewRepo.createQueryBuilder('review')
      .leftJoinAndSelect('review.user', 'user')
      .leftJoinAndSelect('review.room', 'room')
      .leftJoinAndSelect('review.order', 'order');

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

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

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

  async reject(id: number, reason: string) {
    const review = await this.reviewRepo.findOne({ where: { id } });
    if (!review) throw new NotFoundException('评价不存在');

    await this.reviewRepo.update(id, {
      status: 'hidden',
    });
    return { message: '审核拒绝' };
  }
}
