import { NextResponse } from "next/server";

import {
  apiSessionCookieName,
  createApiSessionToken,
  getConfiguredApiAccessKey,
  hasValidApiSession,
} from "../../../../lib/api/auth";

const sessionMaxAgeSeconds = 60 * 60 * 24 * 30;

export async function GET(request: Request) {
  if (process.env.API_AUTH_DISABLED === "true") {
    return NextResponse.json({ authenticated: true });
  }

  const apiAccessKey = getConfiguredApiAccessKey();
  return NextResponse.json({
    authenticated: apiAccessKey
      ? hasValidApiSession(request, apiAccessKey)
      : false,
  });
}

export async function POST(request: Request) {
  if (process.env.API_AUTH_DISABLED === "true") {
    return NextResponse.json({ authenticated: true });
  }

  const apiAccessKey = getConfiguredApiAccessKey();
  if (!apiAccessKey) {
    return NextResponse.json(
      { error: "API access key is not configured" },
      { status: 401 },
    );
  }

  const body = (await request.json().catch(() => ({}))) as {
    api_access_key?: unknown;
    apiAccessKey?: unknown;
  };
  const provided =
    typeof body.api_access_key === "string"
      ? body.api_access_key
      : body.apiAccessKey;

  if (provided !== apiAccessKey) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const response = NextResponse.json({ authenticated: true });
  response.cookies.set({
    name: apiSessionCookieName,
    value: createApiSessionToken(apiAccessKey),
    httpOnly: true,
    sameSite: "lax",
    secure: new URL(request.url).protocol === "https:",
    path: "/",
    maxAge: sessionMaxAgeSeconds,
  });
  return response;
}

export async function DELETE(request: Request) {
  const response = NextResponse.json({ authenticated: false });
  response.cookies.set({
    name: apiSessionCookieName,
    value: "",
    httpOnly: true,
    sameSite: "lax",
    secure: new URL(request.url).protocol === "https:",
    path: "/",
    maxAge: 0,
  });
  return response;
}
