import { NextResponse } from "next/server";

import { auth } from "@/src/auth";
import { deleteArticle, updateArticle, getArticleById } from "@/src/lib/articles";
  
interface RouteContext {
  params: Promise<{ id: string }>;
}

async function readId(params: Promise<{ id: string }>): Promise<number> {
  const { id } = await params;
  const articleId = Number(id);

  if (!Number.isInteger(articleId) || articleId <= 0) {
    throw new Error("ID articolo non valido.");
  }

  return articleId;
}

export async function GET(_request: Request, context: RouteContext) {
  const session = await auth();

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

  try {
    const article = await getArticleById(await readId(context.params));
    return NextResponse.json({ article });
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Articolo non trovato" },
      { status: 404 },
    );
  }
}

export async function PUT(request: Request, context: RouteContext) {
  const session = await auth();

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

  try {
    const article = await updateArticle(await readId(context.params), await request.json());
    return NextResponse.json({ article });
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Errore modifica articolo" },
      { status: 400 },
    );
  }
}

export async function DELETE(_request: Request, context: RouteContext) {
  const session = await auth();

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

  try {
    await deleteArticle(await readId(context.params));
    return NextResponse.json({ ok: true });
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Errore eliminazione articolo" },
      { status: 400 },
    );
  }
}

