import { Injectable, NotFoundException, Logger } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateVipDto, UpdateVipDto } from './dto';

@Injectable()
export class VipsService {
  private readonly logger = new Logger(VipsService.name);

  constructor(private prisma: PrismaService) {}

  async create(createVipDto: CreateVipDto) {
    this.logger.log(`Creating VIP: ${createVipDto.name}`);

    return this.prisma.vIP.create({
      data: createVipDto,
      include: {
        flights: true,
      },
    });
  }

  async findAll() {
    return this.prisma.vIP.findMany({
      where: { deletedAt: null },
      include: {
        flights: true,
      },
      orderBy: { createdAt: 'desc' },
    });
  }

  async findOne(id: string) {
    const vip = await this.prisma.vIP.findFirst({
      where: { id, deletedAt: null },
      include: {
        flights: true,
      },
    });

    if (!vip) {
      throw new NotFoundException(`VIP with ID ${id} not found`);
    }

    return vip;
  }

  async update(id: string, updateVipDto: UpdateVipDto) {
    const vip = await this.findOne(id);

    this.logger.log(`Updating VIP ${id}: ${vip.name}`);

    return this.prisma.vIP.update({
      where: { id: vip.id },
      data: updateVipDto,
      include: {
        flights: true,
      },
    });
  }

  async remove(id: string, hardDelete = false) {
    const vip = await this.findOne(id);

    if (hardDelete) {
      this.logger.log(`Hard deleting VIP: ${vip.name}`);
      return this.prisma.vIP.delete({
        where: { id: vip.id },
      });
    }

    this.logger.log(`Soft deleting VIP: ${vip.name}`);
    return this.prisma.vIP.update({
      where: { id: vip.id },
      data: { deletedAt: new Date() },
    });
  }
}
