import { Injectable } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { InjectDataSource } from '@nestjs/typeorm';
import { DataSource } from 'typeorm';
import { DoctorSlotShift } from './entities/op-hub-doctor-slot-shift-service.entity';

@Injectable()
export class OpHubDoctorSlotShiftServiceService {
  constructor(
    private readonly dynamicConnection: DataSource,
    @InjectDataSource('AdminConnection')
    private readonly connection: DataSource,
    private readonly eventEmitter: EventEmitter2,
  ) { }

  async getShift(Entity: DoctorSlotShift) {
    if (Entity.hospital_id) {
      try {
        let query = `select global_shift.name,global_shift.id shift_id,doctor_global_shift.staff_id
from doctor_global_shift left join global_shift 
on global_shift.id = doctor_global_shift.global_shift_id where staff_id = ? `
        let values = []

        if (Entity.staff_id) {
          values.push(Entity.staff_id)
          const getShifts = await this.dynamicConnection.query(query, values)
          return getShifts
        } else {
          return {
            "message": "Select Doctor to get Shifts"
          }
        }
      } catch (error) {
        return error
      }
    } else {
      return {
        "message": "Enter hospital_id to get shift"
      }
    }
  }

  async getSlot(Entity: DoctorSlotShift, patientId?: number) {
    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 shiftId, 
          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 shiftName,
          doctor_shift.global_shift_id as 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(?)
      `;

      // 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
          )
        `;
        
        var slots = await this.dynamicConnection.query(query, [
          Entity.staff_id,
          Entity.date,
          Entity.staff_id,
          Entity.date,
          patientId
        ]);
      } else {
        // No patient filtering - show all slots
        var slots = await this.dynamicConnection.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 [currentTime] = await this.dynamicConnection.query('SELECT TIME(NOW()) as time');
        slots = slots.filter(slot => slot.end_time >= currentTime.time);
      }

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

      return {
         message: "Available slots found for the selected date",
        available_slots:slots
      };
    } catch (error) {
      return { 
        message: "Error fetching slots", 
        error: error.message 
      };
    }
  }
}