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

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

  listSeatClasses() {
    return this.prisma.seatClass.findMany({ orderBy: { createdAt: 'asc' } });
  }

  async getSeatClass(id: string) {
    const sc = await this.prisma.seatClass.findUnique({ where: { id } });
    if (!sc) throw new NotFoundException('SeatClass not found');
    return sc;
  }

  async createSeatClass(dto: any) {
    try {
      return await this.prisma.seatClass.create({ data: dto });
    } catch (e: any) {
      if (e.code === 'P2002') throw new ConflictException(`Seat class "${dto.name}" already exists`);
      throw e;
    }
  }

  async updateSeatClass(id: string, dto: any) {
    const sc = await this.prisma.seatClass.findUnique({ where: { id } });
    if (!sc) throw new NotFoundException('SeatClass not found');
    return this.prisma.seatClass.update({ where: { id }, data: dto });
  }

  async deleteSeatClass(id: string) {
    const sc = await this.prisma.seatClass.findUnique({ where: { id } });
    if (!sc) throw new NotFoundException('SeatClass not found');
    return this.prisma.seatClass.delete({ where: { id } });
  }
}
