import type { OrganisationSubscription, SubscriptionPlanId, SubscriptionStatus } from './types.js';

export function parseOrganisationSubscription(
  data: unknown,
): OrganisationSubscription | undefined {
  if (!data || typeof data !== 'object') {
    return undefined;
  }

  const record = data as Record<string, unknown>;
  const planId = record.planId;
  const status = record.status;

  if (
    typeof planId !== 'string' ||
    typeof status !== 'string' ||
    !['trial', 'starter', 'professional', 'enterprise'].includes(planId) ||
    !['trialing', 'active', 'past_due', 'canceled', 'expired'].includes(status)
  ) {
    return undefined;
  }

  return {
    planId: planId as SubscriptionPlanId,
    status: status as SubscriptionStatus,
    provider: record.provider === 'payfast' ? 'payfast' : undefined,
    trialEndsAt: typeof record.trialEndsAt === 'string' ? record.trialEndsAt : undefined,
    currentPeriodStart:
      typeof record.currentPeriodStart === 'string' ? record.currentPeriodStart : undefined,
    currentPeriodEnd:
      typeof record.currentPeriodEnd === 'string' ? record.currentPeriodEnd : undefined,
    canceledAt: typeof record.canceledAt === 'string' ? record.canceledAt : undefined,
    billingCycle:
      record.billingCycle === 'monthly' || record.billingCycle === 'annual'
        ? record.billingCycle
        : undefined,
    billingEmail: typeof record.billingEmail === 'string' ? record.billingEmail : undefined,
    payfastToken: typeof record.payfastToken === 'string' ? record.payfastToken : undefined,
    payfastSubscriptionId:
      typeof record.payfastSubscriptionId === 'string' ? record.payfastSubscriptionId : undefined,
    payfastPaymentId:
      typeof record.payfastPaymentId === 'string' ? record.payfastPaymentId : undefined,
  };
}
