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


@Injectable()
export class GoogleauthService {

  constructor(
    private readonly connection: DataSource,
  ) { }
  onApplicationBootstrap(): void {

    this.scheduleTokenInitiation();
  }
  private readonly SCOPES = ['https://www.googleapis.com/auth/firebase.messaging'];
  private accessToken: string | null = null;
  private expiryTime: number | null = null;

  async getAccessToken() {
    const [getFireBaseCredentials] = await this.connection.query(`select * from op_hub_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;
         await this.connection.query(`truncate table op_hub_firebase_auth_bearer_token`)
         await this.connection.query(`insert into op_hub_firebase_auth_bearer_token (token) values (?)`, [
          tokens.access_token
        ])

        const out = tokens
        resolve(out);
      });
    });
  }
  async createCredentials(credentials: any) {

    try {
       await this.connection.query(`truncate table op_hub_firebase_credentials`)
       await this.connection.query(`insert into op_hub_firebase_credentials (credentials) values (?)`, [
        JSON.stringify(credentials)
      ])
      return {
        "status": "success",
        "message": "credentials inserted successfully."
      }
    } catch (error) {
      console.log(error, "error");
    }

  }
  scheduleTokenInitiation(): void {
    console.log("Entering Function");
    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.");
  }

}
