/**
 * Mephonecast Subscription Client (HTTP API).
 * Production API only returns subscribed=true on status/verify when X-Mephonecast-Client: desktop is set
 * (same as the Electron app). Phone apps should not rely on this for Mephonecast entitlements; use Supabase cast RPCs + desktop session for connect limits.
 *
 * Usage:
 *   import { createSubscriptionClient } from './shared/subscriptionClient';
 *   const client = createSubscriptionClient({ apiUrl: 'https://mephonecast-backend.onrender.com' });
 *   const { subscribed } = await client.verify(token);
 */

const DEFAULT_API_URL =
  process.env.MEPHONECAST_API_URL || 'https://mephonecast-backend.onrender.com';

const DESKTOP_HEADERS = { 'X-Mephonecast-Client': 'desktop' };

export function createSubscriptionClient({ apiUrl = DEFAULT_API_URL } = {}) {
  const base = apiUrl.replace(/\/$/, '');

  return {
    async login(email, password) {
      const res = await fetch(`${base}/api/auth/login`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || 'Login failed');
      return data;
    },

    async refresh(refreshToken) {
      const res = await fetch(`${base}/api/auth/refresh`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ refreshToken }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || 'Refresh failed');
      return data;
    },

    /** Diagnostic / non-Electron clients: reads same row the desktop loads from Supabase. Prefer Supabase client + RLS in apps. */
    async getStatus(accessToken) {
      const res = await fetch(`${base}/api/subscription/status`, {
        headers: { ...DESKTOP_HEADERS, Authorization: `Bearer ${accessToken}` },
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || 'Failed to get status');
      return data;
    },

    async verify(accessToken) {
      const res = await fetch(`${base}/api/subscription/verify`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...DESKTOP_HEADERS,
          Authorization: `Bearer ${accessToken}`,
        },
        body: JSON.stringify({}),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || 'Verification failed');
      return data;
    },

    async createCheckout(accessToken, returnOrigin) {
      const res = await fetch(`${base}/api/subscription/checkout`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...DESKTOP_HEADERS,
          Authorization: `Bearer ${accessToken}`,
          ...(returnOrigin && { Origin: returnOrigin, Referer: returnOrigin }),
        },
        body: JSON.stringify({}),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || 'Checkout failed');
      return data;
    },

    async createPortalSession(accessToken, returnOrigin) {
      const res = await fetch(`${base}/api/subscription/portal`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...DESKTOP_HEADERS,
          Authorization: `Bearer ${accessToken}`,
          ...(returnOrigin && { Origin: returnOrigin, Referer: returnOrigin }),
        },
        body: JSON.stringify({}),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || 'Portal failed');
      return data;
    },
  };
}
