import { cookies } from "next/headers";
import { NextResponse } from "next/server";

const TOKEN_KEY = "token";
const MAX_AGE = 365 * 24 * 60 * 60;

function cookieOptions() {
  return {
    path: "/",
    maxAge: MAX_AGE,
    sameSite: "lax" as const,
    secure: process.env.NODE_ENV === "production",
    httpOnly: false,
  };
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const token = typeof body?.token === "string" ? body.token.trim() : "";

    if (!token) {
      return NextResponse.json({ error: "token required" }, { status: 400 });
    }

    const cookieStore = await cookies();
    cookieStore.set(TOKEN_KEY, token, cookieOptions());

    return NextResponse.json({ ok: true });
  } catch {
    return NextResponse.json({ error: "invalid request" }, { status: 400 });
  }
}

export async function DELETE() {
  const cookieStore = await cookies();
  cookieStore.delete({ name: TOKEN_KEY, path: "/" });

  return NextResponse.json({ ok: true });
}
