// Directus-Treiber — CRUD über die Directus REST-API. Collections (products/orders/customers)
// werden vor dem Deploy per Skript provisioniert + geseedet; hier nur Lese-/Schreibzugriff.
const BASE = (process.env.DIRECTUS_URL || '').replace(/\/$/, '');
const TOKEN = process.env.DIRECTUS_TOKEN || '';

async function api(path, opts = {}) {
  const res = await fetch(`${BASE}${path}`, {
    ...opts,
    headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${TOKEN}`, ...(opts.headers || {}) },
  });
  if (!res.ok) throw new Error(`Directus ${res.status} ${path}: ${await res.text().catch(()=> '')}`);
  if (res.status === 204) return null;
  return (await res.json()).data;
}
const arr = (v) => Array.isArray(v) ? v : (v ? (()=>{ try { return JSON.parse(v); } catch { return []; } })() : []);
const P = (r) => r && ({ ...r, sizes: arr(r.sizes), images: arr(r.images), features: arr(r.features), featured: !!r.featured });
const O = (r) => r && ({ ...r, items: arr(r.items) });

export const listProducts = async () => (await api('/items/products?limit=-1&sort=sort,id')).map(P);
export const getProductBySlug = async (slug) => { const d = await api(`/items/products?filter[slug][_eq]=${encodeURIComponent(slug)}&limit=1`); return P(d[0]); };
export const getProductById = async (id) => P(await api(`/items/products/${id}`));
export const createProduct = async (d) => (await api('/items/products', { method:'POST', body: JSON.stringify(payload(d)) })).id;
export const updateProduct = async (id, d) => { await api(`/items/products/${id}`, { method:'PATCH', body: JSON.stringify(payload(d)) }); return id; };
export const deleteProduct = async (id) => { await api(`/items/products/${id}`, { method:'DELETE' }); };
function payload(d){
  const cardImage = d.cardImage || (Array.isArray(d.images)&&d.images[0]) || d.freigestellt || '';
  return { slug:d.slug, name:d.name, shortName:d.shortName||d.name, priceCents:Math.round(Number(d.priceCents)||0), category:d.category||'', productType:d.productType||'physical',
    sizes:d.sizes||['One Size'], images:d.images||[], cardImage, freigestellt:d.freigestellt||'', badge:d.badge||'',
    stock:(d.stock===''||d.stock==null)?null:Math.round(Number(d.stock)), material:d.material||'', features:d.features||[],
    featured:!!d.featured, sort:Number(d.sort)||99, desc:d.desc||'' };
}

export const listOrders = async () => (await api('/items/orders?limit=-1&sort=-created_at')).map(O);
export const getOrderById = async (id) => O(await api(`/items/orders/${id}`));
export async function createOrder({ email, customer_name, items, total_cents, status='pending', address='' }) {
  const existing = await api('/items/orders?limit=1&sort=-id&fields=number');
  let n = 1042; if (existing[0]?.number) { const m = parseInt(String(existing[0].number).split('-')[1]); if (!isNaN(m)) n = m; }
  const number = 'PMPNZNG-' + (n + 1);
  const o = await api('/items/orders', { method:'POST', body: JSON.stringify({ number, email:email||'', customer_name:customer_name||'', status, total_cents:total_cents||0, items:items||[], address:address||'', created_at: new Date().toISOString() }) });
  if (email) { const c = await api(`/items/customers?filter[email][_eq]=${encodeURIComponent(email)}&limit=1`); if (!c.length) await api('/items/customers', { method:'POST', body: JSON.stringify({ name:customer_name||'', email, city:'', created_at:new Date().toISOString() }) }); }
  return { id: o.id, number };
}
export const updateOrderStatus = async (id, status) => { await api(`/items/orders/${id}`, { method:'PATCH', body: JSON.stringify({ status }) }); };

export async function listCustomers() {
  const [customers, orders] = await Promise.all([ api('/items/customers?limit=-1&sort=id'), api('/items/orders?limit=-1&fields=email,total_cents,status') ]);
  return customers.map(c => {
    const mine = orders.filter(o => o.email === c.email && !['cancelled','refunded'].includes(o.status));
    return { ...c, orders_count: mine.length, total_spent_cents: mine.reduce((s,o)=>s+(o.total_cents||0),0) };
  });
}
export const getCustomerById = async (id) => api(`/items/customers/${id}`);

export async function dashboard() {
  const [orders, products, customers] = await Promise.all([ api('/items/orders?limit=-1&sort=-created_at'), api('/items/products?limit=-1'), api('/items/customers?limit=-1&fields=id') ]);
  const paid = orders.filter(o => !['cancelled','refunded'].includes(o.status));
  return {
    revenueCents: paid.reduce((s,o)=>s+(o.total_cents||0),0),
    orderCount: orders.length, productCount: products.length, customerCount: customers.length,
    pending: orders.filter(o=>o.status==='pending').length,
    recentOrders: orders.slice(0,6).map(O),
    lowStock: products.filter(p=>p.stock!=null && p.stock<=25).sort((a,b)=>a.stock-b.stock).map(P),
  };
}
