import { defineBoot } from "#q-app/wrappers";
import { Capacitor } from "@capacitor/core";
import { PushNotifications } from "@capacitor/push-notifications";
import { Preferences } from "@capacitor/preferences";
import { registerDeviceToken } from "src/api/deviceToken";

const FCM_TOKEN_KEY = "pending_fcm_token";

export const registerPendingFcmToken = async () => {
  if (!Capacitor.isNativePlatform()) return;

  const { value } = await Preferences.get({ key: FCM_TOKEN_KEY });
  if (!value) return;

  try {
    const { token, platform } = JSON.parse(value);
    await registerDeviceToken(token, platform);
    await Preferences.remove({ key: FCM_TOKEN_KEY });
  } catch {
    // mantém o token pendente para tentar na próxima autenticação
  }
};

const setupPushNotifications = async () => {
  let permission = await PushNotifications.checkPermissions();

  if (permission.receive === "prompt") {
    permission = await PushNotifications.requestPermissions();
  }

  if (permission.receive !== "granted") {
    return;
  }

  await PushNotifications.register();
};

export default defineBoot(async () => {
  if (!Capacitor.isNativePlatform()) {
    return;
  }

  await PushNotifications.createChannel({
    id: "default",
    name: "Notificações",
    description: "Canal padrão de notificações",
    importance: 4, // HIGH
    visibility: 1, // PUBLIC
    vibration: true,
  }).catch(() => {});

  PushNotifications.addListener("registration", async (token) => {
    const platform = Capacitor.getPlatform();
    await Preferences.set({
      key: FCM_TOKEN_KEY,
      value: JSON.stringify({ token: token.value, platform }),
    });
  });

  PushNotifications.addListener("registrationError", () => {
    // falha silenciosa
  });

  setupPushNotifications();
});
