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

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

export const GET = 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}/suggest-category`, {
      headers: { Authorization: `Bearer ${session.accessToken}` },
    });

    if (!res.ok) {
      const text = await res.text();
      console.error('[api/admin/suggest-category] failed:', res.status, text);
      return Response.json({ error: `AI-kategorisering misslyckades: ${text}` }, { status: res.status });
    }

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