import type { ComplaintVerificationSession } from "../types/complaint.types";

const STORAGE_KEY = "complaint-verification";
const COMPLAINT_VERIFICATION_IDLE_TIMEOUT_MS = 10 * 60 * 1000;

export function storeComplaintVerification(
  session: ComplaintVerificationSession,
): void {
  sessionStorage.setItem(STORAGE_KEY, JSON.stringify(session));
}

export function getComplaintVerification(): ComplaintVerificationSession | null {
  const raw = sessionStorage.getItem(STORAGE_KEY);
  if (!raw) return null;

  try {
    const session = JSON.parse(raw) as ComplaintVerificationSession;
    if (!session.verified) {
      return null;
    }

    const method = session.method ?? "fayda";
    if (method === "fayda" && !session.citizen) {
      return null;
    }
    if (method === "tin" && !session.organization?.tin) {
      return null;
    }

    return { ...session, method };
  } catch {
    clearComplaintVerification();
    return null;
  }
}

export function clearComplaintVerification(): void {
  sessionStorage.removeItem(STORAGE_KEY);
}

export function hasComplaintVerification(): boolean {
  return getComplaintVerification() !== null;
}

export function isComplaintAuthContext(pathname = ""): boolean {
  return (
    pathname.startsWith("/complaints") ||
    pathname === "/complaint-form" ||
    pathname === "/follow-complaint" ||
    pathname === "/callback"
  );
}

export function setupComplaintVerificationIdleCleanup(
  timeoutMs = COMPLAINT_VERIFICATION_IDLE_TIMEOUT_MS,
): () => void {
  let timeoutId: number | null = null;

  const scheduleCleanup = () => {
    if (timeoutId) {
      window.clearTimeout(timeoutId);
    }

    timeoutId = window.setTimeout(() => {
      clearComplaintVerification();
    }, timeoutMs);
  };

  const handleActivity = () => {
    if (!sessionStorage.getItem(STORAGE_KEY)) {
      if (timeoutId) {
        window.clearTimeout(timeoutId);
        timeoutId = null;
      }
      return;
    }

    scheduleCleanup();
  };

  const events: (keyof WindowEventMap)[] = [
    "mousemove",
    "mousedown",
    "keydown",
    "scroll",
    "touchstart",
    "click",
    "focus",
  ];

  events.forEach((eventName) => {
    window.addEventListener(eventName, handleActivity, { passive: true });
  });

  document.addEventListener("visibilitychange", handleActivity);
  handleActivity();

  return () => {
    if (timeoutId) {
      window.clearTimeout(timeoutId);
      timeoutId = null;
    }

    events.forEach((eventName) => {
      window.removeEventListener(eventName, handleActivity);
    });
    document.removeEventListener("visibilitychange", handleActivity);
  };
}
