import * as SecureStore from "expo-secure-store";
import type { MobilePrecheckPayload } from "../types/intervention";

const KEY_PREFIX = "cc_precheck_draft_";
const INDEX_KEY = "cc_precheck_draft_index";

export type StoredPrecheckDraft = MobilePrecheckPayload & {
  saved_at: string;
};

function buildKey(interventionId: number): string {
  return `${KEY_PREFIX}${interventionId}`;
}

async function readIndex(): Promise<number[]> {
  const raw = await SecureStore.getItemAsync(INDEX_KEY);
  if (!raw) {
    return [];
  }

  try {
    const parsed = JSON.parse(raw) as number[];
    return Array.isArray(parsed)
      ? parsed.filter((value) => Number.isInteger(value) && value > 0)
      : [];
  } catch {
    return [];
  }
}

async function writeIndex(ids: number[]): Promise<void> {
  const unique = Array.from(new Set(ids)).filter((value) => Number.isInteger(value) && value > 0);
  if (unique.length === 0) {
    await SecureStore.deleteItemAsync(INDEX_KEY);
    return;
  }

  await SecureStore.setItemAsync(INDEX_KEY, JSON.stringify(unique));
}

export async function savePrecheckDraft(
  payload: MobilePrecheckPayload
): Promise<void> {
  const draft: StoredPrecheckDraft = {
    ...payload,
    saved_at: new Date().toISOString(),
  };
  const key = buildKey(payload.intervention_id);
  await SecureStore.setItemAsync(key, JSON.stringify(draft));

  const ids = await readIndex();
  if (!ids.includes(payload.intervention_id)) {
    await writeIndex([...ids, payload.intervention_id]);
  }
}

export async function getPrecheckDraft(
  interventionId: number
): Promise<StoredPrecheckDraft | null> {
  const raw = await SecureStore.getItemAsync(buildKey(interventionId));
  if (!raw) {
    return null;
  }

  try {
    const parsed = JSON.parse(raw) as StoredPrecheckDraft;
    if (
      typeof parsed.intervention_id !== "number" ||
      typeof parsed.cerfa_enabled !== "boolean"
    ) {
      return null;
    }
    return parsed;
  } catch {
    return null;
  }
}

export async function clearPrecheckDraft(interventionId: number): Promise<void> {
  await SecureStore.deleteItemAsync(buildKey(interventionId));

  const ids = await readIndex();
  await writeIndex(ids.filter((value) => value !== interventionId));
}

export async function clearAllPrecheckDrafts(): Promise<void> {
  const ids = await readIndex();
  await Promise.all(ids.map((id) => SecureStore.deleteItemAsync(buildKey(id))));
  await SecureStore.deleteItemAsync(INDEX_KEY);
}
