import { Injectable } from '@nestjs/common';
import { InjectConnection } from '@nestjs/typeorm';
import { google } from 'googleapis';
import { Connection } from 'typeorm';
import * as cron from 'node-cron';


@Injectable()
export class GoogleauthService {

  constructor(
    @InjectConnection() private connection: Connection,
  ) { }
  onApplicationBootstrap(): void {
    // Trigger the scheduler when the application starts
    this.scheduleTokenInitiation();
  }
  private readonly SCOPES = [process.env.GOOGLE_SCOPES_RESP];
  private accessToken: string | null = null;
  private expiryTime: number | null = null;

  async getAccessToken() {
    const [getFireBaseCredentials] = await this.connection.query(`select * from firebase_credentials`)
    const key = await getFireBaseCredentials.credentials
    const jwtClient = new google.auth.JWT(
      key.client_email,
      null,
      key.private_key,
      this.SCOPES,
      null,
    );

    return new Promise((resolve, reject) => {
      jwtClient.authorize(async (err, tokens) => {
        if (err) {
          reject(err);
          return;
        }
        this.accessToken = tokens.access_token;
        const truncateTable = await this.connection.query(`truncate table firebase_auth_bearer_token`)
        const insertBearerToken = await this.connection.query(`insert into firebase_auth_bearer_token (token) values (?)`, [
          tokens.access_token
        ])
        const out = tokens
        const date = new Date(tokens.expiry_date);
        const damar = new Date()
        resolve(out);
      });
    });
  }
  async createCredentials(credentials: any) {
    try {
      const truncateBeforeInsert = await this.connection.query(`truncate table firebase_credentials`)
      const insertCredentials = await this.connection.query(`insert into firebase_credentials (credentials) values (?)`, [
        JSON.stringify(credentials)
      ])
      return {
        status: process.env.SUCCESS_STATUS_ABHA_ADDRESS_MAPPING,
        "message": "credentials inserted successfully."
      }
    } catch (error) {
      console.log(error, "error");

    }

  }
  scheduleTokenInitiation(): void {
    cron.schedule('0 * * * *', () => {
      console.log('Manually triggering task: Token initiation');
      this.getAccessToken()
        .then(() => {
          console.log('Manually triggered task: Token initiation completed');
        })
        .catch(error => {
          console.error('Error occurred during manual task execution:', error);
        });
    });

    console.log("Scheduled task to run every hour.");
  }

}
