import { auth } from '../firebase';
import type { StorefrontAgreementCatalog } from '../lib/storefrontBridge';
import type {
  IncomingOrderQuote,
  OutboundStudioEvent,
  SkuBomEntry,
  StandardizedInventoryItem,
  StudioPricingRules,
} from '../types';
import type { CollectionAndFormulationCogsSummary } from '../lib/studioOperations';

export interface StorefrontEventRecordView {
  id: string;
  idempotencyKey: string;
  environment: 'staging' | 'production';
  eventType: string;
  track: 'b2b' | 'eczema' | 'menopause';
  referenceCode: string;
  occurredAt: string;
  receivedAt: string;
  contactSummary: {
    firmName?: string;
    contactName: string;
    email: string;
    partnerRole?: string;
  };
  locale: 'en' | 'fr' | 'bilingual';
  province?: string;
  fulfillmentPreference?: 'bulk_studio' | 'direct_homeowner';
  targetDeliveryWindow?: string;
  lineItems: Array<{
    sku?: string;
    storefrontSlug: string;
    variantKey: string;
    name: string;
    qty: number;
    unitPriceCad: number;
  }>;
  subtotalCad: number;
  discountCad: number;
  taxBreakdown: {
    tpsCad: number;
    tvqCad: number;
    hstCad: number;
    totalTaxCad: number;
    estimated: boolean;
  };
  totalCad: number;
  coBrandingOptions: string[];
  requestSampleKit: boolean;
  sanitizedNotes: string;
  healthNotesRedacted: boolean;
  crmLeadCreated: boolean;
  isolatedToSandbox: boolean;
}

export interface StorefrontStatusResponse {
  protocol: string;
  storefrontUrl: string;
  targetEnvironment: 'staging' | 'production';
  ourSharedBaseUrl: string;
  keyConfigured: boolean;
  hmacConfigured: boolean;
  catalog: StorefrontAgreementCatalog;
  stagingEvents: StorefrontEventRecordView[];
  productionEvents: StorefrontEventRecordView[];
}

export interface StudioReferenceDataResponse {
  skuBomCatalog: SkuBomEntry[];
  standardizedInventory: StandardizedInventoryItem[];
  pricingRules: StudioPricingRules;
  cogsSummary: CollectionAndFormulationCogsSummary;
}

export interface StorefrontOperationsResponse {
  incomingOrders: IncomingOrderQuote[];
  outboundQueue: OutboundStudioEvent[];
  referenceData: StudioReferenceDataResponse;
}

async function authorizedStorefrontFetch(path: string, init?: RequestInit): Promise<any> {
  const idToken = await auth.currentUser?.getIdToken();
  if (!idToken) {
    throw new Error('Sign in with your verified Studio Owner account to manage the Storefront connector.');
  }

  const res = await fetch(path, {
    ...init,
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${idToken}`,
      ...(init?.headers || {}),
    },
  });

  const data = await res.json().catch(() => ({}));
  if (!res.ok) {
    throw new Error(data.error || `Storefront connector error (HTTP ${res.status})`);
  }
  return data;
}

export async function fetchStorefrontStatus(): Promise<StorefrontStatusResponse> {
  return authorizedStorefrontFetch('/api/storefront/status', { method: 'GET' });
}

export async function fetchStorefrontOperations(): Promise<StorefrontOperationsResponse> {
  return authorizedStorefrontFetch('/api/storefront/operations', { method: 'GET' });
}

export async function fetchStudioReferenceData(): Promise<StudioReferenceDataResponse> {
  return authorizedStorefrontFetch('/api/storefront/reference-data', { method: 'GET' });
}

export async function syncWorkshopSnapshotToServer(snapshot: any): Promise<{ ok: boolean; syncedAt: string }> {
  return authorizedStorefrontFetch('/api/storefront/sync-state', {
    method: 'POST',
    body: JSON.stringify(snapshot),
  });
}

export async function runIncomingOrderIntake(incomingId: string): Promise<{ ok: boolean; order: IncomingOrderQuote }> {
  return authorizedStorefrontFetch(`/api/storefront/incoming/${encodeURIComponent(incomingId)}/execute`, {
    method: 'POST',
  });
}

export async function evaluateOrderPreviewServer(payload: {
  order: IncomingOrderQuote;
  stateSnapshot?: any;
}): Promise<{ ok: boolean; evaluation: any }> {
  return authorizedStorefrontFetch('/api/storefront/evaluate-preview', {
    method: 'POST',
    body: JSON.stringify(payload),
  });
}

export async function checkSkuBomServer(payload: {
  sku: string;
  quantity: number;
  stateSnapshot?: any;
}): Promise<{ ok: boolean; bom: SkuBomEntry; evaluation: any }> {
  return authorizedStorefrontFetch('/api/storefront/bom-check', {
    method: 'POST',
    body: JSON.stringify(payload),
  });
}

export async function updateOutboundQueueStatus(
  outboundId: string,
  status: 'ready_for_review' | 'approved_copied' | 'resolved',
): Promise<{ ok: boolean; id: string; status: string }> {
  return authorizedStorefrontFetch(`/api/storefront/outbound/${encodeURIComponent(outboundId)}/status`, {
    method: 'POST',
    body: JSON.stringify({ status }),
  });
}

export async function testStorefrontConnection(storefrontUrl?: string): Promise<{
  ok: boolean;
  httpStatus: number;
  targetUrl: string;
  environment: 'staging' | 'production';
  remote: any;
}> {
  return authorizedStorefrontFetch('/api/storefront/test-connection', {
    method: 'POST',
    body: JSON.stringify(storefrontUrl ? { storefrontUrl } : {}),
  });
}

export async function saveAgreedCatalog(catalog: StorefrontAgreementCatalog): Promise<{
  ok: boolean;
  persistedToFirestore: boolean;
  catalog: StorefrontAgreementCatalog;
}> {
  return authorizedStorefrontFetch('/api/storefront/catalog', {
    method: 'PUT',
    body: JSON.stringify(catalog),
  });
}

export async function pushCatalogToStorefront(storefrontUrl?: string): Promise<{
  ok: boolean;
  httpStatus: number;
  targetUrl: string;
  catalogVersion: number;
  skuCount: number;
  remote: any;
}> {
  return authorizedStorefrontFetch('/api/storefront/push-catalog', {
    method: 'POST',
    body: JSON.stringify(storefrontUrl ? { storefrontUrl } : {}),
  });
}

export async function simulateStagingEvent(track: 'b2b' | 'eczema' | 'menopause'): Promise<{
  ok: boolean;
  isolatedToSandbox: boolean;
  crmLeadCreated: boolean;
  record: StorefrontEventRecordView;
  incomingOrder?: IncomingOrderQuote;
}> {
  return authorizedStorefrontFetch('/api/storefront/simulate-staging', {
    method: 'POST',
    body: JSON.stringify({ track }),
  });
}

export async function clearStagingSandbox(): Promise<{ ok: boolean; clearedMemoryCount: number }> {
  return authorizedStorefrontFetch('/api/storefront/staging', {
    method: 'DELETE',
  });
}
