import type { ManagedCaptchaProject, ManagedProjectStore } from "./types.ts";

export class MemoryManagedProjectStore implements ManagedProjectStore {
  private readonly projects = new Map<string, ManagedCaptchaProject>();
  async create(project: ManagedCaptchaProject): Promise<void> {
    if ([...this.projects.values()].some((item) => item.siteKey === project.siteKey))
      throw new Error("Duplicate site key");
    this.projects.set(project.id, structuredClone(project));
  }
  async update(project: ManagedCaptchaProject): Promise<void> {
    if (!this.projects.has(project.id)) throw new Error("Unknown project");
    this.projects.set(project.id, structuredClone(project));
  }
  async getById(id: string) {
    const value = this.projects.get(id);
    return value && structuredClone(value);
  }
  async getBySiteKey(siteKey: string) {
    const value = [...this.projects.values()].find((item) => item.siteKey === siteKey);
    return value && structuredClone(value);
  }
  async getBySecretHash(secretHash: string) {
    const value = [...this.projects.values()].find((item) => item.secretHash === secretHash);
    return value && structuredClone(value);
  }
  async list() {
    return [...this.projects.values()].map((item) => structuredClone(item));
  }
}
