import { Injectable, UnauthorizedException } from "@nestjs/common";
import * as admin from "firebase-admin";
import { UserDevicesService } from "src/user-devices/user-devices.service";

@Injectable()
export class FirebaseProvider {
  constructor(private readonly userDevicesService: UserDevicesService) {
    if (!admin.apps.length) {
      admin.initializeApp({
        credential: admin.credential.cert(
          JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT!),
        ),
      });
    }
  }


  
  

  async send(
    tokens: string[],
    title: string,
    body: string,
    data: Record<string, string>,
  ) {
    if (!tokens.length) return;
    const response = await admin.messaging().sendEachForMulticast({
      tokens,
      notification: { title, body },
      data,
      android : {
        priority: "high",
      },
      apns:{
        headers: {
          "apns-priority": "10",
        },
          payload: {
          aps: {
            sound: "default",
            alert: {
              title,
              body,
            },
          },
        },
      }

    });

    //  AUTO-CLEANUP INVALID TOKENS
    await this.cleanupInvalidTokens(tokens, response);
  }


   async verifyToken(idToken: string) {
    try {
      const decodedToken = await admin.auth().verifyIdToken(idToken);

      if (!decodedToken.email) {
        throw new UnauthorizedException("Email not found in token");
      }

      if (!decodedToken.email_verified) {
        throw new UnauthorizedException("Email not verified");
      }

      return {
        email: decodedToken.email,
        providerId: decodedToken.uid,
        name: decodedToken.name,
        picture: decodedToken.picture,
      };
    } catch (error) {
      console.error("Firebase verification failed:", error);
      throw new UnauthorizedException("Invalid Firebase token");
    }
  }

  private async cleanupInvalidTokens(
    tokens: string[],
    response: admin.messaging.BatchResponse,
  ) {
    const invalidTokens: string[] = [];

    response.responses.forEach((res, index) => {
      if (!res.success) {
        const errorCode = res.error?.code;

        if (
          errorCode === "messaging/registration-token-not-registered" ||
          errorCode === "messaging/invalid-registration-token" ||
          errorCode === "messaging/mismatched-credential"
        ) {
          invalidTokens.push(tokens[index]);
        }
      }
    });

    if (invalidTokens.length) {
      await this.userDevicesService.removeTokens(invalidTokens);
    }
  }
}
