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

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

  constructor(private prisma: PrismaService) {}

  async create(createDriverDto: CreateDriverDto) {
    this.logger.log(`Creating driver: ${createDriverDto.name}`);

    return this.prisma.driver.create({
      data: createDriverDto,
      include: { user: true },
    });
  }

  async findAll() {
    return this.prisma.driver.findMany({
      where: { deletedAt: null },
      include: {
        user: true,
        events: {
          where: { deletedAt: null },
          include: { vehicle: true, driver: true },
          orderBy: { startTime: 'asc' },
        },
      },
      orderBy: { name: 'asc' },
    });
  }

  async findOne(id: string) {
    const driver = await this.prisma.driver.findFirst({
      where: { id, deletedAt: null },
      include: {
        user: true,
        events: {
          where: { deletedAt: null },
          include: { vehicle: true, driver: true },
          orderBy: { startTime: 'asc' },
        },
      },
    });

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

    return driver;
  }

  async findByUserId(userId: string) {
    return this.prisma.driver.findFirst({
      where: { userId, deletedAt: null },
      include: {
        user: true,
        events: {
          where: { deletedAt: null },
          include: { vehicle: true, driver: true },
          orderBy: { startTime: 'asc' },
        },
      },
    });
  }

  async update(id: string, updateDriverDto: UpdateDriverDto) {
    const driver = await this.findOne(id);

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

    return this.prisma.driver.update({
      where: { id: driver.id },
      data: updateDriverDto,
      include: { user: true },
    });
  }

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

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

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

  async getSchedule(id: string) {
    const driver = await this.findOne(id);

    return driver.events;
  }
}
