import { getMessaging } from "firebase-admin/messaging";
import log from "../config/log";
import notificationDB from "../models/notification.model";
import * as admin from "firebase-admin";
//import clientServiceAccount from "../config/client-service.json";
//import tenantServiceAccount from "../config/tenant-service.json";
import { getApp, getApps } from "firebase-admin/app";
import CONSTANTS from "../config/constants";
import fs from "fs";
import path from "path";

interface paramsType {
  title: string;
  message: string;
  regId: string;
  userId: number;
  userType: number;
  notiCategory: number;
  clientId: number;

}

const loadServiceAccount = (filePath: string, defaultPath: string) => {
  let raw: string;

  if (fs.existsSync(filePath)) {
    raw = fs.readFileSync(filePath, "utf-8");
    //console.log(`[ServiceAccount] Loaded: ${filePath}`);
  } else {
    raw = fs.readFileSync(defaultPath, "utf-8");
    // console.warn(
    //   `[ServiceAccount] Missing ${filePath}, using default: ${defaultPath}`
    // );
  }

  return JSON.parse(raw);
};

const sendNotification = async ({
  title,
  message,
  regId,
  userId,
  userType,
  notiCategory = CONSTANTS.NOTIFICATION_CATEGORY.COMPLAIN,
  clientId = 0,
}: paramsType) => {
  try {
    let isClient = true;
    if (userType === CONSTANTS.USER_TYPE.TENANT) {
      isClient = false;
    }

    if ('' === regId || null === regId || undefined === regId) {
      log.info(`[Send Notification], Push Notification, Error: Invalid Registration ID`);
      return false;
    }

    const apps = getApps();

    let clientServiceAcc = null;
    let tenantServiceAcc = null;

    let tenantServiceAccountDefault = path.resolve(`./utils/tenant-app-push-config/google-services.json`);
    let tenantServiceAccountClient = path.resolve(`./utils/tenant-app-push-config/${clientId}/google-services.json`);
    const tenantServiceAccount = loadServiceAccount(tenantServiceAccountClient, tenantServiceAccountDefault);

    let clientServiceAccountPath = path.resolve(`./utils/tenant-app-push-config/client/google-services.json`);
    const clientServiceAccount = loadServiceAccount(clientServiceAccountPath, clientServiceAccountPath);
    if (apps.length > 0) {
      //clientServiceAcc = getApp(clientServiceAccount.project_id);
      //tenantServiceAcc = getApp(tenantServiceAccount.project_id);
      const tAppExists = getApps().some(app => app.name === tenantServiceAccount.project_id);
      if(tAppExists) {
        tenantServiceAcc = getApp(tenantServiceAccount.project_id);
      }

      const cAppExists = getApps().some(app => app.name === clientServiceAccount.project_id);
      if(cAppExists) { 
        clientServiceAcc = getApp(clientServiceAccount.project_id);
      }
    }

    if (!clientServiceAcc) {
      admin.initializeApp(
        {
          credential: admin.credential.cert(
            clientServiceAccount as admin.ServiceAccount
          ),
        },
        clientServiceAccount.project_id
      );
    }

    if (!tenantServiceAcc) {
      admin.initializeApp(
        {
          credential: admin.credential.cert(
            tenantServiceAccount as admin.ServiceAccount
          ),
        },
        tenantServiceAccount.project_id
      );
    }

    const NotiBody = {
      notification: {
        title,
        body: message,
      },
      token: regId,
    };
    log.info(
      `[Send Notification], Push Notification, Sending To [${isClient ? "Client" : "Tenant"}] `
    );
    await getMessaging(isClient ? getApp(clientServiceAccount.project_id) : getApp(tenantServiceAccount.project_id)).send(
      NotiBody
    );

    await notificationDB.add({ userId, userType, title, message, notiCategory });

    return true;
  } catch (error: any) {
    log.info(
      `[Send Notification], Push Notification, Error: ${
        JSON.stringify(error?.response?.data) || error?.message || error
      }`
    );
    await notificationDB.add({ userId, userType, title, message, notiCategory });

    return false;
  }
};

export default sendNotification;
