// Fila de pedidos pendentes de sync (IndexedDB).
// FR-4.2: lançamento funciona completamente offline.
// FR-4.3: Idempotency-Key gerado localmente antes do envio.
// FR-4.11: falhas de sync nunca descartadas silenciosamente.

import type { CreatePedido } from '@sar/api-interface';
import { idbGetAll, idbPut, idbDelete, STORE_PENDING_ORDERS } from './idb';
import { randomUUID } from '../uuid';

export interface PendingOrder {
  idempotencyKey: string; // keyPath do IndexedDB
  payload: CreatePedido;
  clienteNome: string;
  status: 'pending' | 'failed';
  failReason?: string;
  createdAt: string;
}

export function listPendingOrders(): Promise<PendingOrder[]> {
  return idbGetAll<PendingOrder>(STORE_PENDING_ORDERS);
}

export async function enqueueOrder(
  payload: CreatePedido,
  clienteNome: string,
): Promise<PendingOrder> {
  const key = payload.idempotencyKey ?? randomUUID();
  const order: PendingOrder = {
    idempotencyKey: key,
    payload: { ...payload, idempotencyKey: key },
    clienteNome,
    status: 'pending',
    createdAt: new Date().toISOString(),
  };
  await idbPut<PendingOrder>(STORE_PENDING_ORDERS, order);
  return order;
}

export async function removePendingOrder(idempotencyKey: string): Promise<void> {
  return idbDelete(STORE_PENDING_ORDERS, idempotencyKey);
}

export async function markOrderFailed(idempotencyKey: string, reason: string): Promise<void> {
  const all = await listPendingOrders();
  const order = all.find((o) => o.idempotencyKey === idempotencyKey);
  if (!order) return;
  await idbPut<PendingOrder>(STORE_PENDING_ORDERS, {
    ...order,
    status: 'failed',
    failReason: reason,
  });
}

export async function retryPendingOrder(idempotencyKey: string): Promise<void> {
  const all = await listPendingOrders();
  const order = all.find((o) => o.idempotencyKey === idempotencyKey);
  if (!order) return;
  await idbPut<PendingOrder>(STORE_PENDING_ORDERS, {
    ...order,
    status: 'pending',
    failReason: undefined,
  });
  window.dispatchEvent(new CustomEvent('sar:sync-request'));
}
