import type { CouponPreviewResponse } from '@/types/coupon';

function extractErrorMessage(payload: unknown): string {
  if (!payload || typeof payload !== 'object') {
    return 'coupon_error_generic';
  }

  const data = payload as Record<string, unknown>;

  if (typeof data.message === 'string') {
    return data.message;
  }

  if (data.errors && typeof data.errors === 'object') {
    const errors = data.errors as Record<string, unknown>;
    const firstKey = Object.keys(errors)[0];
    const firstEntry = firstKey ? errors[firstKey] : undefined;

    if (Array.isArray(firstEntry) && typeof firstEntry[0] === 'string') {
      return firstEntry[0];
    }
  }

  return 'coupon_error_generic';
}

export async function previewCoupon(packageId: number, code: string): Promise<CouponPreviewResponse> {
  const response = await fetch('/api/v1/marketing/coupons/preview', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    },
    body: JSON.stringify({
      package_id: packageId,
      code,
    }),
  });

  const payload = await response.json().catch(() => ({}));

  if (!response.ok) {
    throw new Error(extractErrorMessage(payload));
  }

  return payload as CouponPreviewResponse;
}
