import { Injectable, ConflictException, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateReservaDto } from './reserva.dto';

@Injectable()
export class SpacesService {
  constructor(private readonly prisma: PrismaService) {}

  async findAll(date?: string) {
    return this.prisma.reserva.findMany({
      where: date ? { date } : undefined,
      orderBy: { createdAt: 'desc' },
    });
  }

  async create(dto: CreateReservaDto) {
    const conflict = await this.prisma.reserva.findUnique({
      where: {
        resourceName_date_startTime: {
          resourceName: dto.resourceName,
          date: dto.date,
          startTime: dto.startTime,
        },
      },
    });

    if (conflict) {
      throw new ConflictException(
        `El recurso "${dto.resourceName}" ya está reservado el ${dto.date} a las ${dto.startTime}.`,
      );
    }

    return this.prisma.reserva.create({ data: dto });
  }

  async delete(id: string): Promise<void> {
    const reserva = await this.prisma.reserva.findUnique({ where: { id } });

    if (!reserva) {
      throw new NotFoundException(`Reserva con id "${id}" no encontrada.`);
    }

    await this.prisma.reserva.delete({ where: { id } });
  }
}
