import { Injectable } from '@nestjs/common';
import { DoctorSlotShift } from './entities/doctor_slot_shift.entity';
import { DataSource } from 'typeorm';

@Injectable()
export class DoctorSlotShiftService {

  constructor(private readonly connection: DataSource) { }

  async getSlot(Entity: DoctorSlotShift, patientId?: number) {
    // Validation checks
    if (!Entity.hospital_id) {
      return {
        message: "Enter hospital_id to get shift"
      };
    }

    if (!Entity.staff_id) {
      return {
        message: "Select Doctor to get Shifts"
      };
    }

    if (!Entity.date) {
      return {
        message: "Select date to get the slots"
      };
    }

    try {
      // Base query to get all doctor shifts for the day
      let query = `
        SELECT 
          doctor_shift.id as shift_id,
          doctor_shift.start_time,
          doctor_shift.end_time,
          CONCAT(doctor_shift.start_time, " - ", doctor_shift.end_time) as slot_timing,
          doctor_shift.day,
          global_shift.name as name,
          doctor_shift.global_shift_id
        FROM doctor_shift
        LEFT JOIN global_shift ON global_shift.id = doctor_shift.global_shift_id
        WHERE doctor_shift.staff_id = ?
        AND doctor_shift.day = DAYNAME(?)
      `;

      let slots;

      // If patientId is provided, exclude only slots where THIS patient has already booked
      if (patientId) {
        query += `
          AND doctor_shift.id NOT IN (
            SELECT shift_id 
            FROM appointment 
            WHERE doctor = ? 
            AND date = ?
            AND patient_id = ?
            AND appointment_status NOT IN ('cancelled', 'rejected')
            AND shift_id IS NOT NULL
          )
        `;
        
        slots = await this.connection.query(query, [
          Entity.staff_id,
          Entity.date,
          Entity.staff_id,
          Entity.date,
          patientId
        ]);
      } else {
        // No patient filtering - show all slots
        slots = await this.connection.query(query, [
          Entity.staff_id,
          Entity.date
        ]);
      }

      // Filter past slots if date is today
      const currentDate = new Date();
      const formattedDate = `${currentDate.getFullYear()}-${(currentDate.getMonth() + 1).toString().padStart(2, '0')}-${currentDate.getDate().toString().padStart(2, '0')}`;
      
      if (Entity.date === formattedDate) {
        const currentTimeResult = await this.connection.query('SELECT TIME(NOW()) as time');
        const currentTime = currentTimeResult[0].time;
        slots = slots.filter(slot => slot.end_time >= currentTime);
      }

      // Check if slots are available
      if (slots.length === 0) {
        return {
          message: "No available slots found for the selected date",
          available_slots: []
        };
      }

      return slots

    } catch (error) {
      return {
        message: "Error fetching slots",
        error: error.message
      };
    }
  }
}