import type { CreateOrderRequest, ApiResponse } from '../types';

const API_BASE = '/api';

const ORDERS_STORAGE_KEY = 'safnaturel_orders';

export async function createOrder(
  order: CreateOrderRequest,
): Promise<{ orderId: number }> {
  try {
    const res = await fetch(`${API_BASE}/orders.php`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(order),
    });

    if (!res.ok) {
      throw new Error(`API error: ${res.status}`);
    }

    const json: ApiResponse<{ orderId: number }> = await res.json();

    if (!json.success || !json.data) {
      throw new Error(json.error ?? 'Sipariş oluşturulamadı');
    }

    return json.data;
  } catch {
    // Fallback: save to localStorage
    return saveOrderToLocalStorage(order);
  }
}

function saveOrderToLocalStorage(
  order: CreateOrderRequest,
): { orderId: number } {
  const existing: Array<CreateOrderRequest & { id: number; createdAt: string }> =
    JSON.parse(localStorage.getItem(ORDERS_STORAGE_KEY) ?? '[]');

  const orderId = existing.length > 0
    ? Math.max(...existing.map((o) => o.id)) + 1
    : 1;

  existing.push({
    ...order,
    id: orderId,
    createdAt: new Date().toISOString(),
  });

  localStorage.setItem(ORDERS_STORAGE_KEY, JSON.stringify(existing));

  return { orderId };
}
