import { Injectable } from '@nestjs/common';
import { InjectConnection } from '@nestjs/typeorm';
import axios from 'axios';
import { Connection } from 'typeorm';


@Injectable()
export class PhrHealthLockerService {
  constructor(@InjectConnection() private connection: Connection,
  

) {

}
  async create(name: string, gender: string, abhaAddress: string, yearOfBirth: number,  hip_id: string) {

    const link_token_requestbody = { name, gender, abhaAddress, yearOfBirth, hip_id}

    const PatientDetails = await link_token_requestbody;
    
    if (abhaAddress) {

      const [checkoldPatientAbhaAddress]:any = await this.connection.query(`select * from patient_abha_address where abhaAddress = ?`, [abhaAddress])

      if(!checkoldPatientAbhaAddress){
        const address_added = await this.connection.query(`insert into patient_abha_address (abhaAddress) values(?)`,[abhaAddress])
      }

      const [checkPatientAbhaAddress]:any = await this.connection.query(`select * from patient_abha_address where abhaAddress = ?`, [abhaAddress])

      if(checkPatientAbhaAddress.link_token_updated_date){
        const givenDate = new Date(
          checkPatientAbhaAddress.link_token_updated_date
        ); // Replace with your date
        const currentDate = new Date();

        // Set time to 00:00:00 for both dates to avoid time issues
        currentDate.setHours(0, 0, 0, 0);
        givenDate.setHours(0, 0, 0, 0);

        // Calculate the difference in months
        const monthDifference =
          (currentDate.getFullYear() - givenDate.getFullYear()) * 12 +
          currentDate.getMonth() -
          givenDate.getMonth();

          if (monthDifference > 5) {
            const getPatnameBody = {
              abhaAddress: abhaAddress,
            };

            const getname = await axios.post(
              "http://13.200.21.111:3333/m1-abha-address-verification",
              getPatnameBody
            );

            const PatName = await getname.data.fullName;
            let patGender;
            if (
              PatientDetails.gender.toLocaleLowerCase() == "male" ||
              PatientDetails.gender.toLocaleLowerCase() == "m"
            ) {
              patGender = "M";
            } else if (
              PatientDetails.gender.toLocaleLowerCase() == "female" ||
              PatientDetails.gender.toLocaleLowerCase() == "f"
            ) {
              patGender = "F";
            } else {
              patGender = "O";
            }

           

            const getLinkTokenBody = await {
              name: await PatName,
              gender: await patGender,
              yearOfBirth: await yearOfBirth,
              abhaAddress: await abhaAddress,
            };
            const headers = await {
              "X-HIP-ID": await hip_id,
              "Content-Type": "application/json",
            };
            console.log(headers, "headerrr", getLinkTokenBody);
            const getLinkToken = await axios.post(
              "http://13.200.21.111:3333/hiecm/api/v3/generate-token",
              getLinkTokenBody,
              { headers }
            );
            console.log(getLinkToken, "getLinkToken");
            

            const updateLinkToken = await this.connection.query(
              `update patient_abha_address set linkToken = ?,
                  link_token_updated_date = date(now()) where abhaAddress = ?`,
              [await getLinkToken.data[0].response[0].payload.linkToken, abhaAddress]
            );
            
          }
          
      }
      else{
        const getPatnameBody = {
          abhaAddress: abhaAddress,
        };

        const getname = await axios.post(
          "http://13.200.21.111:3333/m1-abha-address-verification",
          getPatnameBody
        );

        const PatName = await getname.data.fullName;
        let patGender;
        if (
          PatientDetails.gender.toLocaleLowerCase() == "male" ||
          PatientDetails.gender.toLocaleLowerCase() == "m"
        ) {
          patGender = "M";
        } else if (
          PatientDetails.gender.toLocaleLowerCase() == "female" ||
          PatientDetails.gender.toLocaleLowerCase() == "f"
        ) {
          patGender = "F";
        } else {
          patGender = "O";
        }

        console.log(patGender, "gender");

        const getLinkTokenBody = await {
          name: await PatName,
          gender: await patGender,
          yearOfBirth: await yearOfBirth,
          abhaAddress: await abhaAddress,
        };
        const headers = await {
          "X-HIP-ID": await hip_id,
          "Content-Type": "application/json",
        };
        console.log(headers,"head",getLinkTokenBody);
        
        const getLinkToken = await axios.post(
          "http://13.200.21.111:3333/hiecm/api/v3/generate-token",
          getLinkTokenBody,
          { headers }
        );
        console.log(getLinkToken, "getLinkToken");
        

        const updateLinkToken = await this.connection.query(
          `update patient_abha_address set linkToken = ?,
              link_token_updated_date = date(now()) where abhaAddress = ?`,
          [await getLinkToken.data[0].response[0].payload.linkToken, abhaAddress]
        );

       
      }
    }
    
    else{
      return {
        status: "failed",
        message: "enter abha address to upload doc"
      
      }
      
    }
   
const [link_token] = await this.connection.query(`select linkToken from patient_abha_address where abhaAddress = ?`,[abhaAddress])

return {
  status: "success",
  message: "Document uploaded successfully",
  link_token: link_token.linkToken

}
    

  }
}
