import { NextRequest, NextResponse } from 'next/server';
import { deleteCanvasProject, getCanvasProject, updateCanvasProject } from '@/lib/canvas-store';
import { getAuthenticatedUserId } from '@/lib/session-auth';
import { normalizeCanvasState } from '@/lib/canvas-store';

type RouteContext = {
  params: Promise<{ id: string }>;
};

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

    const { id } = await context.params;
    const project = await getCanvasProject(userId, id);
    if (!project) return NextResponse.json({ error: '画布不存在' }, { status: 404 });

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

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

    const { id } = await context.params;
    const body = await request.json().catch(() => ({}));
    const project = await updateCanvasProject(userId, id, {
      title: typeof body.title === 'string' ? body.title : undefined,
      state: body.state ? normalizeCanvasState(body.state) : undefined,
    });

    if (!project) return NextResponse.json({ error: '画布不存在' }, { status: 404 });
    return NextResponse.json({ project });
  } catch (error) {
    console.error('[canvas/projects/:id] PUT error:', error);
    return NextResponse.json({ error: '保存画布项目失败' }, { status: 500 });
  }
}

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

    const { id } = await context.params;
    const deleted = await deleteCanvasProject(userId, id);
    if (!deleted) return NextResponse.json({ error: '画布不存在' }, { status: 404 });

    return NextResponse.json({ ok: true });
  } catch (error) {
    console.error('[canvas/projects/:id] DELETE error:', error);
    return NextResponse.json({ error: '删除画布项目失败' }, { status: 500 });
  }
}
