import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { ensureSchema, getDb } from '@/lib/db';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

const UpdateBody = z.object({
  title: z.string().optional(),
  description: z.string().optional(),
  transcript: z.string().optional(),
  analysis: z.any().optional(),
  folderId: z.number().int().nullable().optional(),
});

export async function PATCH(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  try {
    await ensureSchema();
    const { id } = await ctx.params;
    const idNum = Number(id);
    if (!idNum || Number.isNaN(idNum)) return NextResponse.json({ error: 'Invalid id' }, { status: 400 });
    const json = await req.json();
    const body = UpdateBody.parse(json);
    const db = getDb();

    // Build dynamic update
    const fields: string[] = [];
    const values: any[] = [];
    if (body.title !== undefined) { fields.push('title = ?'); values.push(body.title); }
    if (body.description !== undefined) { fields.push('description = ?'); values.push(body.description); }
    if (body.transcript !== undefined) { fields.push('transcript = ?'); values.push(body.transcript); }
    if (body.analysis !== undefined) { fields.push('analysis_json = ?'); values.push(JSON.stringify(body.analysis)); }
    if (body.folderId !== undefined) { fields.push('folder_id = ?'); values.push(body.folderId); }
    if (!fields.length) return NextResponse.json({ ok: true });

    values.push(idNum);
    await db.execute(`UPDATE recipes SET ${fields.join(', ')} WHERE id = ?`, values);
    return NextResponse.json({ ok: true });
  } catch (err: any) {
    return NextResponse.json({ error: err?.message || 'Unexpected error' }, { status: 500 });
  }
}


