import { createOrder } from '../../lib/store.js';
export const prerender = false;
const keyLooksReal = (k) => typeof k === 'string' && /^sk_(test|live)_[A-Za-z0-9]{16,}/.test(k.trim());

export async function POST({ request }) {
  let body;
  try { body = await request.json(); } catch { return json({ error: 'Bad request' }, 400); }
  const items = Array.isArray(body.items) ? body.items : [];
  const contact = body.contact || {};
  if (!items.length) return json({ error: 'Warenkorb leer' }, 400);

  const lineItems = items.map((i) => ({
    name: i.name, size: i.size || '', qty: Math.max(1, parseInt(i.qty) || 1),
    priceCents: Math.round(Number(i.price) * 100) || Number(i.priceCents) || 0, image: i.image || '',
  }));
  const subtotal = lineItems.reduce((s, i) => s + i.priceCents * i.qty, 0);
  const shipping = subtotal >= 5000 ? 0 : 490;
  const total = subtotal + shipping;
  const customer_name = [contact.vorname, contact.nachname].filter(Boolean).join(' ').trim();
  const email = contact.email || '';

  const order = await createOrder({ email, customer_name, items: lineItems, total_cents: total, status: 'pending',
    address: [contact.strasse, contact.plz, contact.ort, contact.land].filter(Boolean).join(', ') });

  const secret = process.env.STRIPE_SECRET_KEY || '';
  const origin = new URL(request.url).origin;

  if (keyLooksReal(secret)) {
    try {
      const Stripe = (await import('stripe')).default;
      const stripe = new Stripe(secret);
      const session = await stripe.checkout.sessions.create({
        mode: 'payment', payment_method_types: ['card'], locale: 'de',
        customer_email: email || undefined,
        line_items: [
          ...lineItems.map((i) => ({ quantity: i.qty, price_data: { currency: 'eur', unit_amount: i.priceCents,
            product_data: { name: `${i.name}${i.size ? ' · ' + i.size : ''}` } } })),
          ...(shipping > 0 ? [{ quantity: 1, price_data: { currency: 'eur', unit_amount: shipping, product_data: { name: 'Versand (DE)' } } }] : []),
        ],
        success_url: `${origin}/bestellung-erfolgreich?order=${order.number}`,
        cancel_url: `${origin}/warenkorb`, metadata: { order_number: order.number },
      });
      return json({ url: session.url });
    } catch (e) { return json({ url: `/bestellung-erfolgreich?order=${order.number}&demo=1` }); }
  }
  return json({ url: `/bestellung-erfolgreich?order=${order.number}&demo=1` });
}
function json(obj, status = 200) { return new Response(JSON.stringify(obj), { status, headers: { 'Content-Type': 'application/json' } }); }
