import { jsonResponse, readBody, getAdminPassword } from "../../lib/http";
import { cleanText } from "../../lib/text";
import { adminSessionCookieValue } from "../../lib/auth";

export async function handleAdminSessionPost(
  request: Request,
  env: Env
): Promise<Response> {
  const password = getAdminPassword(env);
  if (!password) {
    return jsonResponse({ ok: false, error: "not_configured" }, 503);
  }

  const data = await readBody(request);
  const token = cleanText(data.token);
  if (token !== password) {
    return jsonResponse({ ok: false, error: "invalid" }, 401);
  }

  const value = await adminSessionCookieValue(env);
  const maxAge = 60 * 60 * 24 * 7;
  const secure = new URL(request.url).protocol === "https:";
  const parts = [`sb_admin=${value}`, "Path=/", "HttpOnly", "SameSite=Lax", `Max-Age=${maxAge}`];
  if (secure) parts.push("Secure");

  return jsonResponse({ ok: true }, 200, {
    "Set-Cookie": parts.join("; ")
  });
}
