import { z } from "zod";
import * as cache from "@lib/cache/cache.ts";

export function createSchema<T extends z.ZodSchema>(name: string, schema: T) {
  type Data = z.infer<T>;
  return {
    async create(input: Omit<Data, "id">): Promise<Data> {
      const data = schema.safeParse(input);
      if (data.success) {
        const d = data.data;
        const id = d["id"];
        if (!id) return d;
        await cache.set(`${name}:${id}`, JSON.stringify(d));
        return d;
      }
      return null;
    },
    async findAll(): Promise<Data[]> {
      const keys = await cache.keys(`${name}:*`);
      return Promise.all(keys.map((k) => {
        return cache.get<string>(k);
      })).then((values) => values.map((v) => JSON.parse(v || "null")));
    },
    async find(id: string) {
      const k = await cache.get<string>(`${name}:${id}`);
      return JSON.parse(k || "null") as Data | null;
    },
    delete(id: string) {
      return cache.del(`${name}:${id}`);
    },
  };
}
