import { Injectable } from '@nestjs/common';
import { CreateOpdPrescriptionDto } from './dto/create-opd-prescription.dto';
import { UpdateOpdPrescriptionDto } from './dto/update-opd-prescription.dto';
import { DataSource } from "typeorm";
import axios from 'axios';
@Injectable()
export class OpdPrescriptionService {
  constructor(private connection: DataSource,
  ) { }
  async create(clinicalNotes: CreateOpdPrescriptionDto | CreateOpdPrescriptionDto[]) {

    const prescriptions = Array.isArray(clinicalNotes) ? clinicalNotes : [clinicalNotes];

    try {
      const [getBaseURL] = await this.connection.query(`select op_hub_base_url from hospitals where plenome_id = ?`, [prescriptions[0].hospital_id])
      const prescription_data = await axios.post(`${getBaseURL.op_hub_base_url}/op-hub-opd-prescription`, prescriptions)
      return prescription_data.data
    } catch (error) {
      throw new Error(error);
    }
  }

  async findAll(opd_id: any, hospital_id: any) {
    if (!hospital_id) {
      return {
        "status": "failed",
        "messege": "enter hospital_id to post clinical notes"
      }
    }

    try {
      const [getBaseURL] = await this.connection.query(`select op_hub_base_url from hospitals where plenome_id = ?`, [hospital_id])
      const prescription_findall = await axios.get(`${getBaseURL.op_hub_base_url}/op-hub-opd-prescription?opd_id=${opd_id}&hospital_id=${hospital_id}`)
      return prescription_findall.data
    }
    catch (error) {
      throw new Error(error);
    }

  }

  async update(clinicalNotes: UpdateOpdPrescriptionDto) {
    if (!clinicalNotes.hospital_id) {
      return {
        "status": "failed",
        "messege": "enter hospital_id to post clinical notes"
      }
    }

    try {
      const [getBaseURL] = await this.connection.query(`select op_hub_base_url from hospitals where plenome_id = ?`, [clinicalNotes.hospital_id])
      const prescription_update = await axios.patch(`${getBaseURL.op_hub_base_url}/op-hub-opd-prescription`, clinicalNotes)
      return prescription_update.data
    }
    catch (error) {
      throw new Error(error);
    }
  }

  async remove(id: number, hospital_id: any) {
    if (!hospital_id) {
      return {
        "status": "failed",
        "messege": "enter hospital_id to post clinical notes"
      }
    }
    try {
      const [getBaseURL] = await this.connection.query(`select op_hub_base_url from hospitals where plenome_id = ?`, [hospital_id])
      const prescription_remove = await axios.delete(`${getBaseURL.op_hub_base_url}/op-hub-opd-prescription?id=${id}&hospital_id=${hospital_id}`)
      return prescription_remove.data
    } catch (error) {
      throw new Error(error);
    }

  }
}
