import { withAuth } from '../../../../../lib/with-auth';

const API_BASE = process.env.NEXT_PUBLIC_API_URL_INTERNAL || 'http://recipe-api:8080';

export const PATCH = withAuth(async (req, session, context) => {
  try {
    const { id } = await context.params;
    const productId = Number(id);
    if (!productId) return Response.json({ error: 'Invalid id' }, { status: 400 });

    const body = await req.json();
    const { name, canonicalName, category, subcategory, brand, categoryId, tags } = body;

    if (!name || typeof name !== 'string' || !name.trim()) {
      return Response.json({ error: 'Namn får inte vara tomt.' }, { status: 400 });
    }

    const authHeader = `Bearer ${session.accessToken}`;

    const patchRes = await fetch(`${API_BASE}/api/products/${productId}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json', Authorization: authHeader },
      body: JSON.stringify({
        name: name.trim(),
        canonicalName: canonicalName?.trim() || undefined,
        category: category?.trim() || null,
        subcategory: subcategory?.trim() || null,
        brand: brand?.trim() || null,
        categoryId: categoryId ?? null,
      }),
    });

    if (!patchRes.ok) {
      const text = await patchRes.text();
      console.error('[api/admin/product] PATCH failed:', patchRes.status, text);
      return Response.json({ error: `Kunde inte uppdatera produkt: ${text}` }, { status: patchRes.status });
    }

    const tagsRes = await fetch(`${API_BASE}/api/products/${productId}/tags`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json', Authorization: authHeader },
      body: JSON.stringify({ tags: tags ?? [] }),
    });

    if (!tagsRes.ok) {
      const text = await tagsRes.text();
      console.error('[api/admin/product] tags PUT failed:', tagsRes.status, text);
      return Response.json({ error: `Kunde inte uppdatera taggar: ${text}` }, { status: tagsRes.status });
    }

    const fullRes = await fetch(`${API_BASE}/api/products/${productId}`, {
      headers: { Authorization: authHeader },
    });

    if (!fullRes.ok) {
      return Response.json({ error: 'Produkt uppdaterad men kunde inte hämtas' }, { status: 500 });
    }

    return Response.json(await fullRes.json());
  } catch (err) {
    console.error('[api/admin/product] PATCH error:', err);
    return Response.json(
      { error: err instanceof Error ? err.message : 'Unknown error' },
      { status: 500 },
    );
  }
});

export const DELETE = withAuth(async (_req, session, context) => {
  try {
    const { id } = await context.params;
    const productId = Number(id);
    if (!productId) return Response.json({ error: 'Invalid id' }, { status: 400 });

    const res = await fetch(`${API_BASE}/api/products/${productId}`, {
      method: 'DELETE',
      headers: { Authorization: `Bearer ${session.accessToken}` },
    });

    if (!res.ok) {
      const text = await res.text();
      console.error('[api/admin/product] DELETE failed:', res.status, text);
      return Response.json({ error: `Kunde inte ta bort produkt: ${text}` }, { status: res.status });
    }

    return new Response(null, { status: 204 });
  } catch (err) {
    console.error('[api/admin/product] DELETE error:', err);
    return Response.json(
      { error: err instanceof Error ? err.message : 'Unknown error' },
      { status: 500 },
    );
  }
});

