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 CreateBody = z.object({ name: z.string().min(1).max(255) });

export async function GET() {
  try {
    await ensureSchema();
    const db = getDb();
    const [rows] = await db.query('SELECT id, name, created_at FROM folders ORDER BY name ASC');
    return NextResponse.json({ folders: rows });
  } 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 = CreateBody.parse(json);
    const db = getDb();
    const [res] = await db.execute('INSERT INTO folders (name) VALUES (?)', [body.name]);
    return NextResponse.json({ id: (res as any).insertId, name: body.name });
  } catch (err: any) {
    return NextResponse.json({ error: err?.message || 'Unexpected error' }, { status: 500 });
  }
}


