import webpush from "web-push";
import { env } from "../config/env.js";

type PushErrorLike = Error & {
  statusCode?: number;
  body?: unknown;
};

let pushConfigured = false;

try {
  webpush.setVapidDetails(env.VAPID_SUBJECT, env.VAPID_PUBLIC_KEY, env.VAPID_PRIVATE_KEY);
  pushConfigured = true;
} catch (error) {
  console.warn(
    "Web Push disabled: failed to initialize VAPID configuration",
    error instanceof Error ? error.message : String(error)
  );
}

export function getVapidPublicKey() {
  return env.VAPID_PUBLIC_KEY;
}

export async function sendWebPush(
  subscription: { endpoint: string; p256dh: string; auth: string },
  payload: Record<string, unknown>
) {
  if (!pushConfigured) {
    return { ok: false, reason: "VAPID not configured" } as const;
  }

  try {
    await webpush.sendNotification(
      {
        endpoint: subscription.endpoint,
        keys: {
          p256dh: subscription.p256dh,
          auth: subscription.auth
        }
      },
      JSON.stringify(payload)
    );

    return { ok: true, statusCode: 201 as const } as const;
  } catch (error) {
    const pushError = error as PushErrorLike;

    return {
      ok: false,
      reason: error instanceof Error ? error.message : "Push error",
      statusCode: pushError?.statusCode,
      details: typeof pushError?.body === "string" ? pushError.body : undefined
    } as const;
  }
}
