import { forwardRef, Inject, Injectable } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { InjectDataSource } from '@nestjs/typeorm';
import { OpHubPreviewDocService } from 'src/op-hub-preview-doc/op-hub-preview-doc.service';
import { DataSource } from 'typeorm';
import { Vital } from './entities/op-hub-vital.entity';

@Injectable()
export class OpHubVitalsService {


  constructor(
    private readonly dynamicConnection: DataSource,
    @InjectDataSource('AdminConnection')
    private readonly connection: DataSource,
    private readonly eventEmitter: EventEmitter2,

  ) { }
  async create(createPrescriptionDto: Vital) {
    if (createPrescriptionDto.Hospital_id) {
      let dynamicConnection;
      try {
        let numb
        try {
          numb = createPrescriptionDto.appointment_id.replace(/[a-zA-Z]/g, '')

        } catch (error) {
          numb = createPrescriptionDto.appointment_id
        }
        const [patientMobHos] = await this.dynamicConnection.query(`select mobileno from patients where id = ?`, [createPrescriptionDto.patient_id])
        const [AdminPatId] = await this.connection.query(`select id from patients where mobileno = ?`, [patientMobHos.mobileno])
        const [appntHOS] = await this.dynamicConnection.query(`select * from appointment where id = ?`, [numb])
        const [AdminApptId] = await this.connection.query(`select id from appointment 
where Hospital_id = ? and hos_appointment_id = ?`, [createPrescriptionDto.Hospital_id,
        appntHOS.id
        ])
        await this.connection.query(`insert into patient_records(patient_id,record_name,files,
      record_type_id,appointment_id) values(?,?,?,?,?)`, [
          AdminPatId.id,
          createPrescriptionDto.record_name,
          createPrescriptionDto.files,
          10,
          AdminApptId.id
        ])
        if (dynamicConnection) {
          dynamicConnection.close();
        }
        return {
          "status": "success",
          "message": "Prescription added successfully"
        }
      } catch (error) {
        return error
      }
    } else {
      return {
        "status": "failed",
        "message": "Enter hospital_id to upload prescription"
      }
    }
  }

  async findAll(createPrescriptionDto: Vital) {
    if (createPrescriptionDto.Hospital_id) {
      if (createPrescriptionDto.patient_id) {

        try {
          const [patientMobHos] = await this.dynamicConnection.query(`select mobileno from patients where id = ?`, [createPrescriptionDto.patient_id])
          const [AdminPatId] = await this.connection.query(`select id from patients where mobileno = ?`, [patientMobHos.mobileno])
          const getPrescr = await this.connection.query(`select patient_records.record_name,patient_records.files,patient_records.tags,
      opd_details.hos_opd_id,concat("Dr. ",staff.name," ",staff.surname) doctorName,CONCAT(DATE_FORMAT(appointment.date, '%D %b %Y'), ",", DATE_FORMAT(appointment.time, '%h:%i %p')) appointDate
             from patient_records
             left join appointment on appointment.id = patient_records.appointment_id
             left join visit_details on visit_details.id = appointment.visit_details_id
             left join opd_details on opd_details.id = visit_details.opd_details_id
             left join staff on staff.id = appointment.doctor
             where patient_records.patient_id = ? and record_type_id = 10`, [AdminPatId.id])
          return getPrescr
        } catch (error) {
          return error
        }
      } else {
        return {
          "status": "failed",
          "message": "Enter hospital_id to get prescription"
        }
      }
    } else {
      return {
        "status": "failed",
        "message": "Enter hospital_id to get prescription"
      }
    }
  }
  async createVitals(vitalsData: any) {
    try {
      const BAD_REQUEST = 400;
      const SERVER_ERROR = 500;
      const SUCCESS = 201;

      // -------------------- Validation --------------------
      if (!vitalsData?.hospital_id) {
        return {
          status: "failed",
          message: "hospital_id is required",
          status_code: BAD_REQUEST,
        };
      }

      if (!vitalsData?.opd_id && !vitalsData?.patient_id) {
        return {
          status: "failed",
          message: "opd_id or patient_id is required",
          status_code: BAD_REQUEST,
        };
      }

      if (!vitalsData?.data) {
        return {
          status: "failed",
          message: "vitals data is required",
          status_code: BAD_REQUEST,
        };
      }

      // -------------------- Variable Declaration --------------------
      let opd_id: number | null = null;
      let patient_id: number | null = null;

      // -------------------- OPD Mapping --------------------
      if (vitalsData.opd_id) {
        const [opdResult]: any = await this.connection.query(
          `SELECT id FROM opd_details WHERE hos_opd_id = ? AND Hospital_id = ?`,
          [vitalsData.opd_id, vitalsData.hospital_id]
        );

        if (opdResult) {
          opd_id = opdResult.id;
        }
      }

      // -------------------- Patient Mapping --------------------
      if (vitalsData.patient_id) {
        const [aayushResult]: any = await this.dynamicConnection.query(
          `SELECT aayush_unique_id FROM patients WHERE id = ?`,
          [vitalsData.patient_id]
        );

        if (aayushResult?.aayush_unique_id) {
          const [patientResult]: any = await this.connection.query(
            `SELECT id FROM patients WHERE aayush_unique_id = ?`,
            [aayushResult.aayush_unique_id]
          );

          if (patientResult) {
            patient_id = patientResult.id;
          }
        }
      }

      // -------------------- Insert Vitals --------------------
      await this.connection.query(
        `INSERT INTO vital_details (opd_id, patient_id, data) VALUES (?, ?, ?)`,
        [opd_id, patient_id, JSON.stringify(vitalsData.data)]
      );

      // -------------------- Success Response --------------------
      return {
        status: "success",
        message: "Vitals data saved successfully",
        status_code: SUCCESS,
      };

    } catch (error) {
      console.error("createVitals error:", error);

      return {
        status: "failed",
        message: "Error saving vitals data",
        status_code: 500,
      };
    }
  }

  async getVitals(vitalsData: any) {
    const BAD_REQUEST = 400;
    const SUCCESS = 200;
    const SERVER_ERROR = 500;
    try {
      // -------------------- Validation --------------------
      if (!vitalsData?.hospital_id) {
        return {
          status: "failed",
          message: "hospital_id is required",
          status_code: BAD_REQUEST,
        };
      }

      if (!vitalsData?.opd_id && !vitalsData?.patient_id) {
        return {
          status: "failed",
          message: "opd_id or patient_id is required",
          status_code: BAD_REQUEST,
        };
      }

      // -------------------- Variable Declaration --------------------
      let opd_id: number | null = null;
      let patient_id: number | null = null;

      // -------------------- OPD Mapping --------------------
      if (vitalsData.opd_id) {
        const [opdResult]: any = await this.connection.query(
          `SELECT id FROM opd_details WHERE hos_opd_id = ? AND Hospital_id = ?`,
          [vitalsData.opd_id, vitalsData.hospital_id]
        );

        if (opdResult) {
          opd_id = opdResult.id;
        }
      }

      // -------------------- Patient Mapping --------------------
      if (vitalsData.patient_id) {
        const [aayushResult]: any = await this.dynamicConnection.query(
          `SELECT aayush_unique_id FROM patients WHERE id = ?`,
          [vitalsData.patient_id]
        );

        if (aayushResult?.aayush_unique_id) {
          const [patientResult]: any = await this.connection.query(
            `SELECT id FROM patients WHERE aayush_unique_id = ?`,
            [aayushResult.aayush_unique_id]
          );

          if (patientResult) {
            patient_id = patientResult.id;
          }
        }
      }

      // -------------------- Fetch Vitals --------------------
      const vitalsQuery = `
      SELECT 
        id,
        opd_id,
        patient_id,
        data,
        created_at
      FROM vital_details
      WHERE 
        (${opd_id ? "opd_id = ?" : "1=1"})
        AND
        (${patient_id ? "patient_id = ?" : "1=1"})
      ORDER BY id DESC
    `;

      const queryParams = [
        ...(opd_id ? [opd_id] : []),
        ...(patient_id ? [patient_id] : []),
      ];

      const vitalsResult = await this.connection.query(vitalsQuery, queryParams);

      // -------------------- Success Response --------------------
      return {
        status: "success",
        message: "Vitals data fetched successfully",
        status_code: SUCCESS,
        data: vitalsResult || [],
      };

    } catch (error) {
      console.error("getVitals error:", error);

      return {
        status: "failed",
        message: "Error fetching vitals data",
        status_code: SERVER_ERROR,
      };
    }
  }

  async updateVitals(vitalsData: any) {
    const BAD_REQUEST = 400;
    const SUCCESS = 200;
    const SERVER_ERROR = 500;

    try {
      // -------------------- Validation --------------------
      if (!vitalsData?.id) {
        return {
          status: "failed",
          message: "vitals id is required",
          status_code: BAD_REQUEST,
        };
      }

      if (!vitalsData?.hospital_id) {
        return {
          status: "failed",
          message: "hospital_id is required",
          status_code: BAD_REQUEST,
        };
      }

      if (!vitalsData?.data) {
        return {
          status: "failed",
          message: "vitals data is required",
          status_code: BAD_REQUEST,
        };
      }

      // -------------------- Check Existing Record --------------------
      const [existingVitals]: any = await this.connection.query(
        `SELECT id FROM vital_details WHERE id = ?`,
        [vitalsData.id]
      );

      if (!existingVitals) {
        return {
          status: "failed",
          message: "Vitals record not found",
          status_code: BAD_REQUEST,
        };
      }

      // -------------------- Update Vitals --------------------
      await this.connection.query(
        `UPDATE vital_details 
       SET data = ? 
       WHERE id = ?`,
        [
          JSON.stringify(vitalsData.data),
          vitalsData.id,
        ]
      );

      // -------------------- Success Response --------------------
      return {
        status: "success",
        message: "Vitals data updated successfully",
        status_code: SUCCESS,
      };

    } catch (error) {
      console.error("updateVitals error:", error);

      return {
        status: "failed",
        message: "Error updating vitals data",
        status_code: SERVER_ERROR,
      };
    }
  }
  async deleteVitalsHard(vitalsData: any) {
    try {
      const BAD_REQUEST = 400;
      const SUCCESS = 200;

      if (!vitalsData?.id) {
        return {
          status: "failed",
          message: "vitals id is required",
          status_code: BAD_REQUEST,
        };
      }

      await this.connection.query(
        `DELETE FROM vital_details WHERE id = ?`,
        [vitalsData.id]
      );

      return {
        status: "success",
        message: "Vitals permanently deleted",
        status_code: SUCCESS,
      };

    } catch (error) {
      console.error("deleteVitalsHard error:", error);

      return {
        status: "failed",
        message: "Error deleting vitals data",
        status_code: 500,
      };
    }
  }

}
