import type { StorageService } from "../types";

export class DatabaseStorageAdapter implements StorageService {
  async get<T>(namespace: string, key: string): Promise<T | null> {
    try {
      const res = await fetch(
        `/api/storage?namespace=${encodeURIComponent(namespace)}&key=${encodeURIComponent(key)}`,
      );
      if (!res.ok) return null;
      const data = await res.json();
      return data.value as T | null;
    } catch (error) {
      console.error("DatabaseStorageAdapter get error:", error);
      return null;
    }
  }

  async set<T>(namespace: string, key: string, value: T): Promise<void> {
    try {
      await fetch("/api/storage", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ namespace, key, value }),
      });
    } catch (error) {
      console.error("DatabaseStorageAdapter set error:", error);
    }
  }

  async delete(namespace: string, key: string): Promise<void> {
    try {
      await fetch(
        `/api/storage?namespace=${encodeURIComponent(namespace)}&key=${encodeURIComponent(key)}`,
        {
          method: "DELETE",
        },
      );
    } catch (error) {
      console.error("DatabaseStorageAdapter delete error:", error);
    }
  }

  async list(namespace: string): Promise<string[]> {
    try {
      const res = await fetch(
        `/api/storage?namespace=${encodeURIComponent(namespace)}`,
      );
      if (!res.ok) return [];
      const data = await res.json();
      return Object.keys(data.items || {});
    } catch (error) {
      console.error("DatabaseStorageAdapter list error:", error);
      return [];
    }
  }

  async query<T>(
    namespace: string,
    predicate: (item: T) => boolean,
  ): Promise<T[]> {
    try {
      const res = await fetch(
        `/api/storage?namespace=${encodeURIComponent(namespace)}`,
      );
      if (!res.ok) return [];
      const data = await res.json();
      const items = Object.values(data.items || {}) as T[];
      return items.filter(predicate);
    } catch (error) {
      console.error("DatabaseStorageAdapter query error:", error);
      return [];
    }
  }

  async clear(namespace: string): Promise<void> {
    try {
      await fetch(`/api/storage?namespace=${encodeURIComponent(namespace)}`, {
        method: "DELETE",
      });
    } catch (error) {
      console.error("DatabaseStorageAdapter clear error:", error);
    }
  }

  async export(
    namespace: string,
    options?: { lightweight?: boolean },
  ): Promise<Record<string, unknown>> {
    try {
      let url = `/api/storage?namespace=${encodeURIComponent(namespace)}`;
      if (options?.lightweight) {
        url += "&lightweight=true";
      }
      const res = await fetch(url);
      if (!res.ok) return {};
      const data = await res.json();
      return data.items || {};
    } catch (error) {
      console.error("DatabaseStorageAdapter export error:", error);
      return {};
    }
  }

  async import(
    namespace: string,
    data: Record<string, unknown>,
  ): Promise<void> {
    try {
      // Import items one by one (or we could create a bulk endpoint, but this is fine for now)
      for (const [key, value] of Object.entries(data)) {
        await this.set(namespace, key, value);
      }
    } catch (error) {
      console.error("DatabaseStorageAdapter import error:", error);
    }
  }
}
