import { NextResponse } from 'next/server';
import { z } from 'zod';
import { prisma } from '@/lib/prisma';
import { requireAdmin } from '@/lib/require-admin';

const faqUpdateInput = z.object({
  serviceId: z.string().nullable().optional(),
  order: z.number().int().optional(),
  translations: z
    .object({
      fr: z.object({ question: z.string(), answer: z.string() }).optional(),
      ar: z.object({ question: z.string(), answer: z.string() }).optional()
    })
    .optional()
});

export async function PATCH(req: Request, { params }: { params: { id: string } }) {
  const { response } = await requireAdmin();
  if (response) return response;

  const parsed = faqUpdateInput.safeParse(await req.json().catch(() => null));
  if (!parsed.success) {
    return NextResponse.json({ error: 'invalid_payload', issues: parsed.error.issues }, { status: 400 });
  }
  const data = parsed.data;

  for (const locale of ['fr', 'ar'] as const) {
    const t = data.translations?.[locale];
    if (t) {
      await prisma.faqTranslation.upsert({
        where: { faqId_locale: { faqId: params.id, locale } },
        update: t,
        create: { faqId: params.id, locale, ...t }
      });
    }
  }

  const faq = await prisma.faq.update({
    where: { id: params.id },
    data: { serviceId: data.serviceId, order: data.order }
  });
  return NextResponse.json(faq);
}

export async function DELETE(_req: Request, { params }: { params: { id: string } }) {
  const { response } = await requireAdmin();
  if (response) return response;
  await prisma.faq.delete({ where: { id: params.id } });
  return NextResponse.json({ ok: true });
}
