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

const authorUpdateInput = z.object({
  avatar: z.string().optional(),
  translations: z
    .object({
      fr: z.object({ name: z.string(), bio: z.string().optional() }).optional(),
      ar: z.object({ name: z.string(), bio: z.string().optional() }).optional()
    })
    .optional()
});

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

  const parsed = authorUpdateInput.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.authorTranslation.upsert({
        where: { authorId_locale: { authorId: params.id, locale } },
        update: t,
        create: { authorId: params.id, locale, ...t }
      });
    }
  }

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

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