import { archiveProject, getProject, updateProject } from '../../../../lib/projects.js';
import { requireSession } from '@/lib/auth.js';
export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';

function catchAuth(err) {
  if (err && typeof err === 'object' && err.status) {
    return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
  }
  return null;
}

export async function GET(req, { params }) {
  try {
    await requireSession(req);
    const { slug } = await params;
    const project = getProject(slug);
    return project ? Response.json({ project }) : Response.json({ error: 'not found' }, { status: 404 });
  } catch (err) {
    return catchAuth(err) ?? Response.json({ error: err.message }, { status: 500 });
  }
}
export async function PATCH(req, { params }) {
  try {
    await requireSession(req);
    const { slug } = await params;
    const project = updateProject(slug, await req.json());
    return project ? Response.json({ project }) : Response.json({ error: 'not found' }, { status: 404 });
  } catch (err) {
    return catchAuth(err) ?? Response.json({ error: err.message }, { status: 500 });
  }
}
export async function DELETE(req, { params }) {
  try {
    await requireSession(req);
    const { slug } = await params;
    const project = archiveProject(slug);
    return project ? Response.json({ project }) : Response.json({ error: 'not found' }, { status: 404 });
  } catch (err) {
    return catchAuth(err) ?? Response.json({ error: err.message }, { status: 500 });
  }
}
