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 SaveBody = z.object({
  url: z.string().url(),
  platform: z.enum(['tiktok', 'instagram', 'unknown']),
  title: z.string().optional().default(''),
  description: z.string().optional().default(''),
  transcript: z.string().optional().default(''),
  analysis: z.any(),
  thumbnailBase64: z.string().optional(),
  folderId: z.number().int().nullable().optional(),
});

export async function GET() {
  try {
    await ensureSchema();
    const db = getDb();
    const [rows] = await db.query(
      'SELECT id, created_at, source_url, platform, description, transcript, CAST(analysis_json AS CHAR) AS analysis_json, thumbnail FROM recipes ORDER BY id DESC LIMIT 100',
    );
    const list = (rows as any[]).map((r) => ({
      id: r.id,
      created_at: r.created_at,
      url: r.source_url,
      platform: r.platform,
      description: r.description,
      transcript: r.transcript,
      analysis: (() => { try { return JSON.parse(r.analysis_json); } catch { return null; } })(),
      thumbnailBase64: r.thumbnail ? `data:image/jpeg;base64,${Buffer.from(r.thumbnail).toString('base64')}` : null,
    }));
    return NextResponse.json({ recipes: list });
  } catch (err: any) {
    return NextResponse.json({ error: err?.message || 'Unexpected error' }, { status: 500 });
  }
}

export async function POST(req: NextRequest) {
  try {
    await ensureSchema();
    const json = await req.json();
    const body = SaveBody.parse(json);

    const db = getDb();
    const thumbBuf = body.thumbnailBase64?.startsWith('data:')
      ? Buffer.from(body.thumbnailBase64.split(',')[1] || '', 'base64')
      : body.thumbnailBase64
        ? Buffer.from(body.thumbnailBase64, 'base64')
        : null;
    const [res] = await db.execute(
      'INSERT INTO recipes (source_url, platform, title, description, transcript, analysis_json, thumbnail, folder_id) VALUES (?,?,?,?,?,?,?,?)',
      [body.url, body.platform, body.title, body.description, body.transcript, JSON.stringify(body.analysis), thumbBuf, body.folderId ?? null],
    );
    const id = (res as any).insertId;
    return NextResponse.json({ id });
  } catch (err: any) {
    return NextResponse.json({ error: err?.message || 'Unexpected error' }, { status: 500 });
  }
}


