// import { Injectable } from '@nestjs/common';

// @Injectable()
// export class AppService {
//   getHello(): string {
//     return 'Hello World!';
//   }

// }

import { Injectable, OnModuleInit } from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
import { DataSource } from 'typeorm';

@Injectable()
export class AppService implements OnModuleInit {
  constructor(
    private readonly dynamicConnection: DataSource,
    @InjectDataSource('AdminConnection')
    private readonly connection: DataSource,
  ) { }
  async onModuleInit() {
    try {
      await this.connection.query(`
        CREATE TABLE IF NOT EXISTS user_payment_summary(
          id INT AUTO_INCREMENT PRIMARY KEY,
          user_id INT,
          wallet_amount_paid varchar(50),
          paid_amount varchar(50),
          due_amount varchar(50),
          actual_amount_paid varchar(50),
          total_online_payments varchar(50),
          total_offline_payments varchar(50),
          total_billed_amount varchar(50),
          total_tax_amount varchar(50),
          overall_subtotal_amount varchar(50),
          created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )
      `);
    } catch (error) {
      console.error(
        'Failed to create user_payment_summary table :',
        error.message,
      );
    }
    try {
      await this.connection.query(`
        CREATE TABLE IF NOT EXISTS patient_payment_summary(
          id INT AUTO_INCREMENT PRIMARY KEY,
          patient_id INT,
          wallet_amount_paid varchar(50),
          paid_amount varchar(50),
          due_amount varchar(50),
          actual_amount_paid varchar(50),
          total_online_payments varchar(50),
          total_offline_payments varchar(50),
          total_billed_amount varchar(50),
          total_tax_amount varchar(50),
          overall_subtotal_amount varchar(50),
          created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )
      `);
    } catch (error) {
      console.error(
        'Failed to create patient_payment_summary :',
        error.message,
      );
    }
    try {
      await this.dynamicConnection.query(`
        CREATE TABLE IF NOT EXISTS patient_payment_summary(
          id INT AUTO_INCREMENT PRIMARY KEY,
          patient_id INT,
          wallet_amount_paid varchar(50),
          paid_amount varchar(50),
          due_amount varchar(50),
          actual_amount_paid varchar(50),
          total_online_payments varchar(50),
          total_offline_payments varchar(50),
          total_billed_amount varchar(50),
          total_tax_amount varchar(50),
          overall_subtotal_amount varchar(50),
          created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )
      `);
    } catch (error) {
      console.error('Failed to create user_payment_summary :', error.message);
    }
    try {
      await this.connection.query(`
        CREATE TABLE IF NOT EXISTS hospital_payment_summary(
          id INT AUTO_INCREMENT PRIMARY KEY,
          hospital_id INT,
          wallet_amount_paid varchar(50),
          paid_amount varchar(50),
          due_amount varchar(50),
          actual_amount_paid varchar(50),
          total_online_payments varchar(50),
          total_offline_payments varchar(50),
          total_billed_amount varchar(50),
          total_tax_amount varchar(50),
          overall_subtotal_amount varchar(50),
          created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )
      `);

      console.log('Tables created successfully');
    } catch (error) {
      console.error(
        'Failed to create hospital_payment_summary :',
        error.message,
      );
    }

    try {
      await this.connection.query(`
    ALTER TABLE patients
    ADD COLUMN existing_patient_id int(10),
    ADD COLUMN employer_id int(15),
    ADD COLUMN employer_name VARCHAR(100),
    ADD COLUMN employee_id int(50),
    ADD COLUMN occupation VARCHAR(100);
  `);
    } catch (error) {
      console.error('Failed to update patients table:', error.message);
    }

    try {
      await this.dynamicConnection.query(`
    ALTER TABLE patients
    ADD COLUMN existing_patient_id int(10),
    ADD COLUMN employer_id int(15),
    ADD COLUMN employer_name VARCHAR(100),
    ADD COLUMN employee_id int(50),
    ADD COLUMN occupation VARCHAR(100);
  `);
    } catch (error) {
      console.error('Failed to update patients table:', error.message);
    }

    try {
      await this.dynamicConnection.query(`
    ALTER TABLE patients
MODIFY COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
  `);
    } catch (error) {
      console.error('Failed to update patients table:', error.message);
    }

    try {
      await this.connection.query(`
    ALTER TABLE patients
MODIFY COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
  `);
    } catch (error) {
      console.error('Failed to update patients table:', error.message);
    }

    try {
      await this.connection.query(`
       
    CREATE TABLE IF NOT EXISTS aayush_coins  (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    total_coins_used INT NOT NULL DEFAULT 0,
    total_coins_remaining INT NOT NULL DEFAULT 0,
    total_coins_issued INT NOT NULL DEFAULT 0,
    coins_expiry_time DATETIME NOT NULL,
    is_expired BOOLEAN NOT NULL DEFAULT FALSE,
    coins_usage ENUM('fully_used', 'partially_used', 'not_used') NOT NULL DEFAULT 'not_used',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY (id)
)`);
    } catch (error) {
      console.error('Failed to create aayush_coins table :', error.message);
    }

    try {
      await this.connection.query(`ALTER TABLE plenome_ADMIN.aayush_coins 
CHANGE COLUMN total_coins_used total_coins_used FLOAT NOT NULL DEFAULT '0' ,
CHANGE COLUMN total_coins_remaining total_coins_remaining FLOAT NOT NULL DEFAULT '0' ,
CHANGE COLUMN total_coins_issued total_coins_issued FLOAT NOT NULL DEFAULT '0'`);
    } catch (error) {
      console.error('Failed to update aayush_coins table :', error.message);
    }

    try {
      await this.connection.query(`ALTER TABLE plenome_ADMIN.users 
CHANGE COLUMN password password VARCHAR(50) NULL `);
    } catch (error) {
      console.error('Failed to alter user table :', error.message);
    }

    try {
      await this.connection.query(`ALTER TABLE plenome_ADMIN.users 
CHANGE COLUMN has_mpin has_mpin TINYINT(1) NULL DEFAULT 0 ;`);
    } catch (error) {
      console.error('Failed to alter user table :', error.message);
    }

    try {
      await this.dynamicConnection.query(`
    CREATE TABLE IF NOT EXISTS opd_voice_data (
      id INT UNSIGNED NOT NULL AUTO_INCREMENT,
      aayush_unique_id VARCHAR(50) NOT NULL,
      user_id INT NOT NULL,
      type ENUM('general','dental') NOT NULL,
      transcript_id VARCHAR(50) DEFAULT NULL,
      opd_details_id INT NOT NULL,
      data JSON DEFAULT NULL,
      audio_file TEXT,
      hospital_id INT DEFAULT NULL,
      created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
      updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (id),
      KEY fk_opd_details (opd_details_id),
      CONSTRAINT fk_opd_details FOREIGN KEY (opd_details_id) 
        REFERENCES opd_details (id) 
        ON DELETE CASCADE ON UPDATE CASCADE
    );
  `);
      console.log('opd_voice_data table is ready');
    } catch (error) {
      console.error('Failed to create opd_voice_data:', error.message);
    }

    try {
      await this.connection.query(`
    ALTER TABLE transactions
    ADD COLUMN actual_paid_amount VARCHAR(100) DEFAULT '0.00',
    ADD COLUMN wallet_paid_amount VARCHAR(100) DEFAULT '0.00'
  `);
    } catch (error) {
      console.error('Failed to update transactions table:', error.message);
    }

    try {
      await this.dynamicConnection.query(`
    ALTER TABLE transactions
    ADD COLUMN actual_paid_amount VARCHAR(100) DEFAULT '0.00',
    ADD COLUMN wallet_paid_amount VARCHAR(100) DEFAULT '0.00'
  `);
    } catch (error) {
      console.error('Failed to update transactions table:', error.message);
    }
    try {
      await this.connection.query(`
        CREATE TABLE plenome_ADMIN.coin_value (
  id INT NOT NULL AUTO_INCREMENT,
  coin_amount INT NOT NULL DEFAULT 1,  
  currency_code VARCHAR(10) NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT current_timestamp,
  PRIMARY KEY (id)
        )
      `);
    } catch (error) {
      console.error('Failed to create coin_value table :', error.message);
    }

    try {
      await this.connection.query(`
        ALTER TABLE plenome_ADMIN.aayush_coins 
ADD COLUMN module VARCHAR(50) NULL DEFAULT 'FREE COINS' AFTER updated_at
      `);
    } catch (error) {
      console.error('Failed to create coin_value table :', error.message);
    }
    try {
      await this.connection.query(`
        ALTER TABLE plenome_ADMIN.coin_value
CHANGE COLUMN coin_amount coin_amount DECIMAL(10,2) NOT NULL DEFAULT '1.00'
      `);
    } catch (error) {
      console.error('Failed to create coin_value table :', error.message);
    }
    try {
      const check = await this.connection.query(
        `select * from plenome_ADMIN.coin_value `,
      )
      if (check.length < 1) {
        await this.connection.query(`
        insert into coin_value (coin_amount, currency_code) values(?,?)
      `,
          [1.0, 'INR'],
        );
      }

    } catch (error) {
      console.error('Failed to create coin_value table :', error.message);
    }
    try {
      await this.dynamicConnection.query(`ALTER TABLE transactions 
ADD COLUMN partial_payment_mode VARCHAR(45) NULL DEFAULT NULL AFTER wallet_paid_amount
`);
    } catch (error) {
      console.error('Failed to update transactions table:', error.message);
    }
    try {
      await this.connection.query(`ALTER TABLE transactions 
ADD COLUMN partial_payment_mode VARCHAR(45) NULL DEFAULT NULL AFTER wallet_paid_amount
`);
    } catch (error) {
      console.error('Failed to update transactions table:', error.message);
    }

    try {
      await this.dynamicConnection.query(`ALTER TABLE transactions 
ADD COLUMN partial_payment_date VARCHAR(45) NULL DEFAULT NULL AFTER wallet_paid_amount
`);
    } catch (error) {
      console.error('Failed to update transactions table:', error.message);
    }
    try {
      await this.connection.query(`ALTER TABLE transactions 
ADD COLUMN partial_payment_date VARCHAR(45) NULL DEFAULT NULL AFTER wallet_paid_amount
`);
    } catch (error) {
      console.error('Failed to update transactions table:', error.message);
    }

    try {
      await this.connection.query(`
    ALTER TABLE transactions
    ADD COLUMN temp_actual_paid_amount VARCHAR(100) DEFAULT '0.00',
    ADD COLUMN temp_wallet_paid_amount VARCHAR(100) DEFAULT '0.00'
  `);
    } catch (error) {
      console.error('Failed to update transactions table:', error.message);
    }

    try {
      await this.dynamicConnection.query(`
    ALTER TABLE transactions
    ADD COLUMN temp_actual_paid_amount VARCHAR(100) DEFAULT '0.00',
    ADD COLUMN temp_wallet_paid_amount VARCHAR(100) DEFAULT '0.00'
  `);
    } catch (error) {
      console.error('Failed to update transactions table:', error.message);
    }

    try {
      await this.connection.query(`CREATE TABLE bundle_diagnostic_units (
    id INT AUTO_INCREMENT PRIMARY KEY,
    unit_name VARCHAR(50) NOT NULL
)`);
    } catch (error) {
      console.error('Failed to create bundle_diagnostic_units:', error.message);
    }

    try {
      await this.connection
        .query(`INSERT INTO bundle_diagnostic_units (unit_name) VALUES
('mg/dL'),
('g/dL'),
('U/L'),
('IU/L'),
('mmol/L'),
('µIU/mL'),
('ng/mL'),
('pg/mL'),
('µg/dL'),
('%'),
('cells/µL'),
('/HPF'),
('mg/L'),
('ng/dL'),
('mEq/L'),
('µg/mL'),
('g/L'),
('fL'),
('pg'),
('K/µL'),
('M/µL'),
('µmol/L'),
('nmol/L'),
('µg/L'),
('ratio'),
('mL/min'),
('IU/mL'),
('mg/24hr'),
('µg/24hr'),
('mmHg'),
('°C');`);
    } catch (error) {
      console.error('Failed to insert bundle_diagnostic_units:', error.message);
    }

    try {
      await this.connection.query(`ALTER TABLE staff 
ADD COLUMN esi_number VARCHAR(45) NULL AFTER is_deleted;
`)
    } catch (error) {

    }
    try {
      await this.dynamicConnection.query(`ALTER TABLE staff 
ADD COLUMN esi_number VARCHAR(45) NULL AFTER is_deleted;
`)
    } catch (error) {

    }

    try {
      await this.connection.query(`ALTER TABLE patient_charges 
ADD COLUMN temp_payment_status VARCHAR(45) NULL DEFAULT NULL ;
`)
    } catch (error) {

    }
    try {
      await this.dynamicConnection.query(`ALTER TABLE patient_charges 
ADD COLUMN temp_payment_status VARCHAR(45) NULL DEFAULT NULL ;
`)
    } catch (error) {

    }
    try {
      await this.dynamicConnection.query(`ALTER TABLE patient_charges 
ADD COLUMN package_id int NULL DEFAULT NULL ;
`)
    } catch (error) {

    }
    try {
      await this.connection.query(`ALTER TABLE patient_charges 
ADD COLUMN package_id int NULL DEFAULT NULL ;
`)
    } catch (error) {

    }
    try {
      await this.connection.query(`ALTER TABLE aayush_coins 
DROP INDEX user_id ;
`)
    } catch (error) {

    }

    try {
      await this.connection.query(`UPDATE staff_leave_request
SET employee_remark = ''
WHERE employee_remark IS NULL;
`)
      await this.connection.query(`UPDATE staff_leave_request
SET admin_remark = ''
WHERE admin_remark IS NULL;`)
      await this.connection.query(`UPDATE staff_leave_request
SET document_file = ''
WHERE document_file IS NULL;`)
      await this.connection.query(`ALTER TABLE staff_leave_request 
CHANGE COLUMN employee_remark employee_remark TEXT NOT NULL  ,
CHANGE COLUMN admin_remark admin_remark TEXT NOT NULL ,
CHANGE COLUMN document_file document_file TEXT NOT NULL ;
`)
    } catch (error) {
      console.log(error, "er");

    }
    try {
      await this.dynamicConnection.query(`UPDATE staff_leave_request
SET employee_remark = ''
WHERE employee_remark IS NULL;
`)
      await this.dynamicConnection.query(`UPDATE staff_leave_request
SET admin_remark = ''
WHERE admin_remark IS NULL;`)
      await this.dynamicConnection.query(`UPDATE staff_leave_request
SET document_file = ''
WHERE document_file IS NULL;`)
      await this.dynamicConnection.query(`ALTER TABLE staff_leave_request 
CHANGE COLUMN employee_remark employee_remark TEXT NOT NULL ,
CHANGE COLUMN admin_remark admin_remark TEXT NOT NULL ,
CHANGE COLUMN document_file document_file TEXT NOT NULL ;
`)
    } catch (error) {
      console.log(error, "errr");

    }

    try {
      await this.connection.query(`ALTER TABLE staff_leave_request 
CHANGE COLUMN employee_remark employee_remark TEXT NULL ,
CHANGE COLUMN admin_remark admin_remark TEXT NULL ,
CHANGE COLUMN document_file document_file TEXT NULL ;
`)
    } catch (error) {

    }
    try {
      await this.dynamicConnection.query(`ALTER TABLE staff_leave_request 
CHANGE COLUMN employee_remark employee_remark TEXT NULL ,
CHANGE COLUMN admin_remark admin_remark TEXT NULL ,
CHANGE COLUMN document_file document_file TEXT NULL ;
`)
    } catch (error) {

    }

    try {
      await this.connection.query(`ALTER TABLE leave_types 
DROP INDEX type ;

`)
    } catch (error) {

    }
    try {
      await this.connection.query(`CREATE TABLE vital_details (
  id INT NOT NULL AUTO_INCREMENT,
  opd_id INT NULL,
  patient_id INT NULL,
  data JSON NULL,
  created_at TIMESTAMP NULL DEFAULT current_timestamp,
  PRIMARY KEY (id));
`)
    } catch (error) {

    }

  }


  getHello(): string {
    return 'Hello World!';
  }
}
