import * as functions from 'firebase-functions'
import { applyEntitlementSync, EntitlementState } from './entitlementLogic'

/**
 * Callable function that forces a re-sync of entitlements for the
 * authenticated caller.
 *
 * Request body: { } (auth context supplies uid)
 * Response: EntitlementState
 *
 * The client can invoke this after a purchase/restore or when local
 * entitlement state appears stale. In production this should fetch the
 * latest entitlement state from RevenueCat; for now it computes the
 * state from the existing Firestore document and rewrites it, ensuring
 * consistent field shapes.
 */
export const syncEntitlement = functions.https.onCall(async (data, context) => {
  if (!context.auth?.uid) {
    throw new functions.https.HttpsError(
      'unauthenticated',
      'Caller must be authenticated.'
    )
  }

  const userId = context.auth.uid

  try {
    const state = await applyEntitlementSync(userId)
    return state satisfies EntitlementState
  } catch (err) {
    console.error('[syncEntitlement] failed:', err)
    throw new functions.https.HttpsError(
      'internal',
      'Entitlement sync failed.'
    )
  }
})
