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

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

  /**
   * 用户提交评价（通过订单号）
   */
  async createByOrderNo(userId: number, orderNo: string, dto: CreateReviewDto) {
    const order = await this.orderRepo.findOne({ where: { orderNo } });
    if (!order) throw new NotFoundException('订单不存在');
    if (order.userId !== userId) throw new ForbiddenException('无权操作此订单');
    if (order.status !== 'completed') throw new BadRequestException('只有已完成的订单才能评价');

    // 检查是否已评价
    const existing = await this.reviewRepo.findOne({ where: { orderId: order.id } });
    if (existing) throw new BadRequestException('该订单已评价');

    if (dto.rating < 1 || dto.rating > 5) throw new BadRequestException('评分范围为1-5');

    const review = this.reviewRepo.create({
      orderId: order.id,
      userId,
      merchantId: order.merchantId,
      roomId: order.roomId,
      rating: dto.rating,
      content: dto.content,
      images: dto.images,
      isAnonymous: dto.isAnonymous || false,
      status: 'pending',
    });

    await this.reviewRepo.save(review);
    return { message: '评价已提交' };
  }

  /**
   * 用户提交评价（通过订单ID，保留用于内部调用）
   */
  async create(userId: number, orderId: number, dto: CreateReviewDto) {
    const order = await this.orderRepo.findOne({ where: { id: orderId } });
    if (!order) throw new NotFoundException('订单不存在');
    if (order.userId !== userId) throw new ForbiddenException('无权操作此订单');
    if (order.status !== 'completed') throw new BadRequestException('只有已完成的订单才能评价');

    // 检查是否已评价
    const existing = await this.reviewRepo.findOne({ where: { orderId } });
    if (existing) throw new BadRequestException('该订单已评价');

    if (dto.rating < 1 || dto.rating > 5) throw new BadRequestException('评分范围为1-5');

    const review = this.reviewRepo.create({
      orderId,
      userId,
      merchantId: order.merchantId,
      roomId: order.roomId,
      rating: dto.rating,
      content: dto.content,
      images: dto.images,
      isAnonymous: dto.isAnonymous || false,
      status: 'pending',
    });

    await this.reviewRepo.save(review);
    return { message: '评价已提交' };
  }

  /**
   * 查询评价列表（公开，只显示可见的）
   */
  async findPublic(query: QueryReviewDto) {
    const { page = 1, pageSize = 10, merchantId, roomId } = query;
    const qb = this.reviewRepo
      .createQueryBuilder('r')
      .leftJoinAndSelect('r.order', 'o')
      .where('r.status = :status', { status: 'visible' });

    if (merchantId) {
      qb.andWhere('r.merchant_id = :merchantId', { merchantId: Number(merchantId) });
    }
    if (roomId) {
      qb.andWhere('r.room_id = :roomId', { roomId: Number(roomId) });
    }

    qb.orderBy('r.createdAt', 'DESC');
    const safePage = Number(page) || 1;
    const safePageSize = Number(pageSize) || 10;
    qb.skip((safePage - 1) * safePageSize).take(safePageSize);

    const [list, total] = await qb.getManyAndCount();
    return { list, total, page: safePage, pageSize: safePageSize, totalPages: Math.ceil(total / safePageSize) };
  }

  /**
   * 检查订单是否已评价（通过订单号）
   */
  async findByOrderNo(orderNo: string) {
    const order = await this.orderRepo.findOne({ where: { orderNo } });
    if (!order) return null;
    return this.reviewRepo.findOne({ where: { orderId: order.id } });
  }

  /**
   * 检查订单是否已评价（通过订单ID）
   */
  async findByOrder(orderId: number) {
    return this.reviewRepo.findOne({ where: { orderId } });
  }
}
