import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Guest } from '@/entities/guest.entity';
import { CreateGuestDto, UpdateGuestDto } from './dto/guest.dto';

@Injectable()
export class GuestService {
  constructor(
    @InjectRepository(Guest)
    private readonly guestRepository: Repository<Guest>,
  ) {}

  async create(userId: number, dto: CreateGuestDto): Promise<Guest> {
    // 如果设置为默认，先取消其他默认常住人
    if (dto.isDefault) {
      await this.guestRepository.update(
        { userId, isDefault: true },
        { isDefault: false },
      );
    }

    const guest = this.guestRepository.create({
      userId,
      ...dto,
    });

    return await this.guestRepository.save(guest);
  }

  async findAll(userId: number): Promise<Guest[]> {
    return await this.guestRepository.find({
      where: { userId },
      order: { isDefault: 'DESC', createdAt: 'DESC' },
    });
  }

  async findById(id: number, userId: number): Promise<Guest> {
    const guest = await this.guestRepository.findOne({
      where: { id, userId },
    });

    if (!guest) {
      throw new NotFoundException('常住人不存在');
    }

    return guest;
  }

  async update(id: number, userId: number, dto: UpdateGuestDto): Promise<Guest> {
    const guest = await this.findById(id, userId);

    // 如果设置为默认，先取消其他默认常住人
    if (dto.isDefault) {
      await this.guestRepository.update(
        { userId, isDefault: true, id: { $ne: id } as any },
        { isDefault: false },
      );
    }

    Object.assign(guest, dto);
    return await this.guestRepository.save(guest);
  }

  async delete(id: number, userId: number): Promise<void> {
    const guest = await this.findById(id, userId);
    await this.guestRepository.remove(guest);
  }

  async setDefault(id: number, userId: number): Promise<void> {
    const guest = await this.findById(id, userId);

    // 取消其他默认常住人
    await this.guestRepository.update(
      { userId, isDefault: true },
      { isDefault: false },
    );

    // 设置当前为默认
    guest.isDefault = true;
    await this.guestRepository.save(guest);
  }
}
