import { NextRequest, NextResponse } from 'next/server';
import { createCanvasProject, listCanvasProjects } from '@/lib/canvas-store';
import { getAuthenticatedUserId } from '@/lib/session-auth';

export async function GET(request: NextRequest) {
  try {
    const userId = await getAuthenticatedUserId(request);
    if (!userId) return NextResponse.json({ error: '请先登录' }, { status: 401 });

    const projects = await listCanvasProjects(userId);
    return NextResponse.json({ projects });
  } catch (error) {
    console.error('[canvas/projects] GET error:', error);
    return NextResponse.json({ error: '读取画布项目失败' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const userId = await getAuthenticatedUserId(request);
    if (!userId) return NextResponse.json({ error: '请先登录' }, { status: 401 });

    const body = await request.json().catch(() => ({}));
    const title = typeof body.title === 'string' ? body.title : '未命名画布';
    const project = await createCanvasProject(userId, title);
    return NextResponse.json({ project }, { status: 201 });
  } catch (error) {
    console.error('[canvas/projects] POST error:', error);
    return NextResponse.json({ error: '创建画布项目失败' }, { status: 500 });
  }
}
