import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { PrismaService } from '../../../prisma/prisma.service';
import { BookingRecordsService } from './records.service';

export interface AddToWaitlistDto {
  clientName: string;
  clientPhone: string;
  serviceId: string;
  staffId?: string;
  preferredDate?: string;
  preferredTime?: string;
  notes?: string;
}

@Injectable()
export class WaitlistService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly recordsService: BookingRecordsService,
  ) {}

  async findAll(clubId: string) {
    return this.prisma.bookingWaitlist.findMany({
      where: { clubId, convertedRecordId: null },
      orderBy: { createdAt: 'asc' },
    });
  }

  async add(clubId: string, dto: AddToWaitlistDto) {
    return this.prisma.bookingWaitlist.create({
      data: {
        clubId,
        clientName: dto.clientName,
        clientPhone: dto.clientPhone,
        serviceId: dto.serviceId,
        staffId: dto.staffId,
        preferredDate: dto.preferredDate ? new Date(dto.preferredDate) : undefined,
        preferredTime: dto.preferredTime,
        notes: dto.notes,
      },
    });
  }

  async convertToRecord(id: string, params: { staffId: string; startAt: string }, userId?: string) {
    const entry = await this.prisma.bookingWaitlist.findUnique({ where: { id } });
    if (!entry) throw new NotFoundException(`Waitlist entry ${id} not found`);
    if (entry.convertedRecordId) {
      throw new BadRequestException('Already converted to a booking');
    }

    const record = await this.recordsService.create(
      entry.clubId,
      {
        clientName: entry.clientName,
        clientPhone: entry.clientPhone,
        serviceId: entry.serviceId,
        staffId: params.staffId,
        startAt: params.startAt,
        source: 'WAITLIST',
      },
      userId,
    );

    await this.prisma.bookingWaitlist.update({
      where: { id },
      data: { convertedRecordId: record.id },
    });

    return record;
  }

  async delete(id: string) {
    const entry = await this.prisma.bookingWaitlist.findUnique({ where: { id } });
    if (!entry) throw new NotFoundException(`Waitlist entry ${id} not found`);
    await this.prisma.bookingWaitlist.delete({ where: { id } });
  }
}
