import { forwardRef, Inject, Injectable } from '@nestjs/common';
import { OpHubPreviewDocService } from 'src/op-hub-preview-doc/op-hub-preview-doc.service';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { InjectDataSource } from '@nestjs/typeorm';
import axios from 'axios';
import { awsConfig } from 'src/aws.config';
import { DataSource } from 'typeorm';
import { v4 as uuidv4 } from 'uuid';
import { S3, GetObjectCommand } from '@aws-sdk/client-s3';

@Injectable()
export class OpHubUploadDocPreviewService {
  constructor(
    private readonly dynamicConnection: DataSource,
    @InjectDataSource('AdminConnection')
    private readonly connection: DataSource,
    private readonly eventEmitter: EventEmitter2,
    @Inject(forwardRef(() => OpHubPreviewDocService))
    private docPreviewData: OpHubPreviewDocService,
  ) { }

  async create(
    file: any,
    opd_id: number,
    hospital_id: number,
    abhaAddress: string,
  ) {
    console.log(
      file,
      ': any',
      opd_id,
      ': number',
      hospital_id,
      ': number',
      abhaAddress,
      ': string',
    );

    if (!hospital_id) {
      return {
        status: 'failed',
        messege: 'enter hospital_id to post clinical notes',
      };
    }
    const [getPatientID] = await this.dynamicConnection.query(
      `select patient_id from opd_details where id = ?`,
      [opd_id],
    );

    const [checkPatientAbhaAddress] = await this.dynamicConnection.query(
      `select * from patient_abha_address where abhaAddress = ?`,
      [abhaAddress],
    );
    console.log(checkPatientAbhaAddress, 'checkPatientAbhaAddress');

    const [getPatDOB] = await this.dynamicConnection.query(
      `select * from patients where id = ?`,
      [getPatientID.patient_id],
    );
    let yob;
    if (getPatDOB.dob) {
      const [getYob] = await this.dynamicConnection.query(
        `SELECT YEAR(dob) AS year FROM patients where id = ?`,
        [getPatientID.patient_id],
      );
      yob = await getYob.year;
    }

    try {
      await this.dynamicConnection.query(
        `update visit_details set case_sheet_document = ? where opd_details_id = ?`,
        [file, opd_id],
      );
      const [getAdminOPD] = await this.connection.query(
        `select id from opd_details where Hospital_id = ? and hos_opd_id = ?`,
        [hospital_id, opd_id],
      );
      await this.connection.query(
        `update visit_details set case_sheet_document = ? where opd_details_id = ?`,
        [file, getAdminOPD.id],
      );

      return {
        status: 'success',
        message: 'case sheet uploaded successfully',
        data: file,
      };
    } catch (error) {
      return {
        status: 'failed',
        message: 'unable to upload case sheet',
        error,
      };
    }
  }
  async updateLinkToken(
    hospital_id: number,
    token: string,
    abhaAddress: string,
  ) {
    try {
      await this.dynamicConnection.query(
        `update patient_abha_address set linkToken = ?,
            link_token_updated_date = date(now()) where abhaAddress = ?`,
        [token, abhaAddress],
      );
    } catch (error) {
      console.log(error);
    }
  }

  async getexistingLinkToken(hospital_id: number, abhaAddress: string) {
    try {
      const [existing_link_token] = await this.dynamicConnection.query(
        `select linkToken from patient_abha_address where abhaAddress = ?`,
        [abhaAddress],
      );
      return existing_link_token;
    } catch (error) {
      console.log(error);
    }
  }

  async findAll(value: string) {
    try {
      const s3 = new S3({
        credentials: {
          accessKeyId: awsConfig.accessKeyId,
          secretAccessKey: awsConfig.secretAccessKey,
        },
        region: awsConfig.region,
      });

      const command = new GetObjectCommand({
        Bucket: awsConfig.bucketName,
        Key: value,
      });

      const s3Data = await s3.send(command);

      const buffer = Buffer.from(await s3Data.Body.transformToByteArray());
      return buffer.toString('base64');
    } catch (error) {
      console.error(error);
      return error;
    }
  }


  async uploadDoc(
    file: string,
    opd_id: number,
    hospital_id: number,
  ) {

    try {
      await this.dynamicConnection.query(
        `update visit_details set case_sheet_document = ? where opd_details_id = ?`,
        [file, opd_id],
      );
      const [getAdminOPD] = await this.connection.query(
        `select id from opd_details where Hospital_id = ? and hos_opd_id = ?`,
        [hospital_id, opd_id],
      );
      await this.connection.query(
        `update visit_details set case_sheet_document = ? where opd_details_id = ?`,
        [file, getAdminOPD.id],
      );

      return {
        status: 'success',
        message: 'case sheet uploaded successfully',
      };
    } catch (error) {
      return {
        statusCode: 500,
        status: 'failed',
        message: 'unable to upload case sheet',
      };
    }
  }
}
