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

const registerPushNotifications = 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(() => {
  if (!Capacitor.isNativePlatform()) {
    return;
  }

  PushNotifications.addListener("registration", async (token) => {
    const platform = Capacitor.getPlatform();
    try {
      await registerDeviceToken(token.value, platform);
    } catch {
      // falha silenciosa — não bloqueia o uso do app
    }
  });

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

  registerPushNotifications();
});
