import fs from "node:fs";
import path from "node:path";
import type { BrowserContext } from "playwright";
import { resolveStorageStatePath } from "@/lib/axel/session";

export function getStorageStatePath(): string {
  return resolveStorageStatePath();
}

export function invalidateStorageState(): void {
  const statePath = getStorageStatePath();
  if (fs.existsSync(statePath)) {
    fs.unlinkSync(statePath);
  }
}

export async function persistContext(context: BrowserContext): Promise<void> {
  const statePath = getStorageStatePath();
  const dir = path.dirname(statePath);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
  await context.storageState({ path: statePath });
}

export function storageStateExists(): boolean {
  return fs.existsSync(getStorageStatePath());
}

export function getStorageStateForContext(
  overridePath?: string,
): { storageState: string } | Record<string, never> {
  const candidate = overridePath?.trim() || getStorageStatePath();
  if (fs.existsSync(candidate)) {
    return { storageState: candidate };
  }
  return {};
}
