import { NextRequest, NextResponse } from "next/server";

export const ADMIN_AUTH_SESSION_HEADER = "x-admin-authenticated";
export const ADMIN_TRAFFIC_TOKEN_HEADER = "x-traffic-token";

const ADMIN_USERNAME = (process.env.ADMIN_USERNAME || process.env.WOOO_ADMIN_USERNAME || "").trim();
const ADMIN_PASSWORD = (process.env.ADMIN_PASSWORD || process.env.WOOO_ADMIN_PASSWORD || "").trim();
const HAS_ADMIN_CREDENTIALS = Boolean(ADMIN_USERNAME) && Boolean(ADMIN_PASSWORD);
const TRAFFIC_MONITOR_TOKEN = process.env.TRAFFIC_MONITOR_TOKEN?.trim();

if (!HAS_ADMIN_CREDENTIALS && process.env.NODE_ENV === "production") {
  console.error("[admin-auth] ADMIN_USERNAME / ADMIN_PASSWORD must be configured in production.");
}

type BasicCredential = {
  username: string;
  password: string;
};

function parseBasicAuth(headerValue: string): BasicCredential | null {
  const cleaned = headerValue.trim();
  if (!cleaned.startsWith("Basic ")) {
    return null;
  }

  const encoded = cleaned.slice(6);
  if (!encoded) {
    return null;
  }

  let decoded = "";
  try {
    decoded = Buffer.from(encoded, "base64").toString("utf8");
  } catch {
    return null;
  }

  const divider = decoded.indexOf(":");
  if (divider < 0) {
    return null;
  }

  return {
    username: decoded.slice(0, divider),
    password: decoded.slice(divider + 1),
  };
}

function isCredentialMatched(username: string, password: string) {
  return username === ADMIN_USERNAME && password === ADMIN_PASSWORD;
}

export function resolveAdminAccount() {
  return {
    username: ADMIN_USERNAME,
    isDefaultCredentials: false,
  };
}

export function isAdminRequestAuthorized(request: NextRequest | Request) {
  if (!HAS_ADMIN_CREDENTIALS) {
    return false;
  }

  const authorization = request.headers.get("authorization");
  if (authorization) {
    const credentials = parseBasicAuth(authorization);
    if (credentials && isCredentialMatched(credentials.username, credentials.password)) {
      return true;
    }
  }

  return false;
}

export function adminUnauthorizedResponse() {
  const response = NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  response.headers.set("WWW-Authenticate", 'Basic realm="VibeWork Admin", charset="UTF-8"');
  return response;
}

export function attachAdminHeaders(request: NextRequest) {
  const requestHeaders = new Headers(request.headers);
  requestHeaders.delete(ADMIN_AUTH_SESSION_HEADER);
  requestHeaders.delete(ADMIN_TRAFFIC_TOKEN_HEADER);
  requestHeaders.set(ADMIN_AUTH_SESSION_HEADER, "1");
  if (TRAFFIC_MONITOR_TOKEN) {
    requestHeaders.set(ADMIN_TRAFFIC_TOKEN_HEADER, TRAFFIC_MONITOR_TOKEN);
  }
  return requestHeaders;
}

export function stripClientAdminHeaders(request: NextRequest) {
  const requestHeaders = new Headers(request.headers);
  requestHeaders.delete(ADMIN_AUTH_SESSION_HEADER);
  requestHeaders.delete(ADMIN_TRAFFIC_TOKEN_HEADER);
  return requestHeaders;
}
