import { NextResponse } from "next/server";

import { auth } from "@/src/auth";
import { createArticle, listArticles, listFamilies } from "@/src/lib/articles";

export async function GET() {
  const session = await auth();

  if (!session?.user) {
    return NextResponse.json({ error: "Non autenticato" }, { status: 401 });
  }

  const [articles, families] = await Promise.all([listArticles(), listFamilies()]);

  return NextResponse.json({ articles, families });
}

export async function POST(request: Request) {
  const session = await auth();

  if (!session?.user) {
    return NextResponse.json({ error: "Non autenticato" }, { status: 401 });
  }

  try {
    const article = await createArticle(await request.json());
    return NextResponse.json({ article }, { status: 201 });
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Errore creazione articolo" },
      { status: 400 },
    );
  }
}

