export type PlaywrightStorageState = {
  cookies?: unknown[];
  origins?: unknown[];
};

export function normalizeStorageStateInput(
  input: string | PlaywrightStorageState
): { ok: true; storageState: string } | { ok: false; error: string } {
  let parsed: PlaywrightStorageState;

  if (typeof input === "string") {
    const trimmed = input.trim();
    if (!trimmed) {
      return { ok: false, error: "storageState 不可為空" };
    }
    try {
      parsed = JSON.parse(trimmed) as PlaywrightStorageState;
    } catch {
      return { ok: false, error: "storageState 不是有效的 JSON" };
    }
  } else {
    parsed = input;
  }

  if (!Array.isArray(parsed.cookies)) {
    return { ok: false, error: "storageState 缺少 cookies 陣列，請確認是 Playwright 匯出的格式" };
  }

  return { ok: true, storageState: JSON.stringify(parsed) };
}