import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { getCurrentUser } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

/**
 * PATCH  /api/ai/templates/[id]  — edit. User-owned templates: any
 *                                   user. Built-in templates (userId
 *                                   IS NULL): admin only. Note that
 *                                   admin edits to built-ins do NOT
 *                                   survive the next boot's reconcile
 *                                   pass — to ship lasting changes,
 *                                   edit prisma/aiTemplates.seed.json.
 * DELETE /api/ai/templates/[id]  — same admin gate for built-ins.
 */

const patchSchema = z.object({
  name: z.string().min(1).optional(),
  description: z.string().optional().nullable(),
  systemPrompt: z.string().min(1).optional(),
  userPromptTemplate: z.string().min(1).optional(),
});

async function loadAndCheck(
  templateId: string,
  user: { id: string; isAdmin: boolean },
) {
  const tpl = await prisma.aIPromptTemplate.findUnique({
    where: { id: templateId },
  });
  if (!tpl) return { tpl: null, error: 'Template not found' as const, code: 404 };
  // Ownership: user templates can only be touched by their owner;
  // built-ins (userId=null) can only be touched by admins.
  if (tpl.userId == null) {
    if (!user.isAdmin) {
      return {
        tpl: null,
        error:
          'Built-in template — admin only. Clone-to-edit if you want a personal copy.',
        code: 403 as const,
      };
    }
  } else if (tpl.userId !== user.id) {
    return { tpl: null, error: 'Not your template', code: 403 as const };
  }
  return { tpl, error: null, code: 200 as const };
}

export async function PATCH(
  request: NextRequest,
  { params }: { params: { id: string } },
) {
  try {
    const user = await getCurrentUser();
    if (!user)
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const { tpl, error, code } = await loadAndCheck(params.id, user);
    if (!tpl) return NextResponse.json({ error }, { status: code });

    const body = await request.json().catch(() => ({}));
    const parsed = patchSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json(
        { error: 'Invalid body', details: parsed.error.errors },
        { status: 400 },
      );
    }
    const updated = await prisma.aIPromptTemplate.update({
      where: { id: params.id },
      data: parsed.data,
    });
    return NextResponse.json(updated);
  } catch (err) {
    console.error('PATCH /api/ai/templates/[id] error:', err);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 },
    );
  }
}

export async function DELETE(
  _request: NextRequest,
  { params }: { params: { id: string } },
) {
  try {
    const user = await getCurrentUser();
    if (!user)
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const { tpl, error, code } = await loadAndCheck(params.id, user);
    if (!tpl) return NextResponse.json({ error }, { status: code });

    await prisma.aIPromptTemplate.delete({ where: { id: params.id } });
    return NextResponse.json({ success: true });
  } catch (err) {
    console.error('DELETE /api/ai/templates/[id] error:', err);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 },
    );
  }
}
