import type { ZodSchema } from "zod";

const PREFIX = "afl_";

function prefixed(key: string): string {
  return `${PREFIX}${key}`;
}

export const storage = {
  get<T>(key: string, schema: ZodSchema<T>): T | null {
    try {
      const raw = localStorage.getItem(prefixed(key));
      if (raw === null) return null;
      const parsed: unknown = JSON.parse(raw);
      const result = schema.safeParse(parsed);
      return result.success ? result.data : null;
    } catch {
      return null;
    }
  },

  set<T>(key: string, value: T, schema: ZodSchema<T>): void {
    schema.parse(value);
    localStorage.setItem(prefixed(key), JSON.stringify(value));
  },

  delete(key: string): void {
    localStorage.removeItem(prefixed(key));
  },

  clear(): void {
    const keysToRemove: string[] = [];
    for (let i = 0; i < localStorage.length; i++) {
      const k = localStorage.key(i);
      if (k?.startsWith(PREFIX)) {
        keysToRemove.push(k);
      }
    }
    for (const k of keysToRemove) {
      localStorage.removeItem(k);
    }
  },
};
