import { createClient } from "@supabase/supabase-js";
import { cookies } from "next/headers";
import { supabaseUrl } from "./supabase/config";

export const developerEmail = (process.env.DEVELOPER_ADMIN_EMAIL ?? "dmarksolutionbd@gmail.com").trim().toLowerCase();
const sessionSeconds = 60 * 60 * 12;

function configuredSecret() {
  const secret = process.env.DEVELOPER_COOKIE_SECRET;
  return secret && secret.length >= 32 ? secret : null;
}

async function signatureFor(payload: string, secret: string) {
  const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(payload));
  return Array.from(new Uint8Array(signature)).map((value) => value.toString(16).padStart(2, "0")).join("");
}

function safeEqual(left: string, right: string) {
  if (left.length !== right.length) return false;
  let mismatch = 0;
  for (let index = 0; index < left.length; index++) mismatch |= left.charCodeAt(index) ^ right.charCodeAt(index);
  return mismatch === 0;
}

export async function createDeveloperToken(email: string, password: string) {
  const configuredPassword = process.env.DEVELOPER_ADMIN_PASSWORD;
  const secret = configuredSecret();
  if (!configuredPassword || !secret || email.trim().toLowerCase() !== developerEmail || !safeEqual(password, configuredPassword)) return null;
  const expiresAt = Math.floor(Date.now() / 1000) + sessionSeconds;
  return `${expiresAt}.${await signatureFor(`${developerEmail}:${expiresAt}`, secret)}`;
}

export async function requireDeveloper() {
  const secret = configuredSecret();
  if (!secret) return null;
  const cookieStore = await cookies();
  const supplied = cookieStore.get("planexa_developer")?.value;
  const [expiresRaw, signature] = supplied?.split(".") ?? [];
  const expiresAt = Number(expiresRaw);
  if (!expiresAt || expiresAt <= Math.floor(Date.now() / 1000) || !signature) return null;
  const expected = await signatureFor(`${developerEmail}:${expiresAt}`, secret);
  if (!safeEqual(signature, expected)) return null;
  return { id: "website-owner", email: developerEmail };
}

export function createDeveloperDatabaseClient() {
  const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
  if (!serviceKey) return null;
  return createClient(supabaseUrl, serviceKey, { auth: { autoRefreshToken: false, persistSession: false } });
}
