"use server";

import { timingSafeEqual } from "node:crypto";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { z } from "zod";
import { ROLES, ROUTES } from "@/lib/constants";
import { getRegionCodes } from "@/lib/regions";

const localViewerSchema = z.object({
  role: z.enum([ROLES.admin, ROLES.affiliate]),
  scope: z.string().trim().toUpperCase().optional().default(""),
  accessPassword: z.string().trim().min(1),
});

const COOKIE_MAX_AGE = 60 * 60 * 24 * 30;

function resolveExpectedPassword(input: { role: "admin" | "affiliate"; scope: string }) {
  const fallback = (process.env.LOCAL_ACCESS_PASSWORD ?? "").trim();
  const adminPassword = (process.env.LOCAL_ACCESS_PASSWORD_ADMIN ?? "").trim();
  const regionalDefault = (process.env.LOCAL_ACCESS_PASSWORD_REGIONAL ?? "").trim();
  const scopedPassword = input.scope
    ? (process.env[`LOCAL_ACCESS_PASSWORD_${input.scope}`] ?? "").trim()
    : "";

  if (input.role === ROLES.admin) {
    return adminPassword || fallback;
  }

  return scopedPassword || regionalDefault || fallback;
}

function safePasswordEquals(a: string, b: string) {
  const left = Buffer.from(a);
  const right = Buffer.from(b);
  if (left.length !== right.length) return false;
  return timingSafeEqual(left, right);
}

export async function setLocalViewerAction(formData: FormData) {
  const parsed = localViewerSchema.safeParse({
    role: formData.get("role") ?? undefined,
    scope: formData.get("scope") ?? undefined,
    accessPassword: formData.get("access_password") ?? undefined,
  });

  if (!parsed.success) {
    redirect(`${ROUTES.login}?error=invalid-local-viewer`);
  }

  const { role, scope, accessPassword } = parsed.data;
  const isValidScope = getRegionCodes().includes(scope);
  if (role === ROLES.affiliate && !isValidScope) {
    redirect(`${ROUTES.login}?error=invalid-scope`);
  }

  const expectedPassword = resolveExpectedPassword({ role, scope });

  if (!expectedPassword || !safePasswordEquals(accessPassword, expectedPassword)) {
    redirect(`${ROUTES.login}?error=invalid-access-password`);
  }

  const cookieStore = await cookies();

  cookieStore.set("local_viewer_role", role, {
    path: "/",
    sameSite: "strict",
    maxAge: COOKIE_MAX_AGE,
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
  });

  if (role === ROLES.affiliate && isValidScope) {
    cookieStore.set("local_viewer_scope", scope, {
      path: "/",
      sameSite: "strict",
      maxAge: COOKIE_MAX_AGE,
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
    });
  } else {
    cookieStore.delete("local_viewer_scope");
  }

  redirect(ROUTES.dashboard);
}
