import { useEffect, useState, useCallback } from "preact/hooks";
import type { RecordSpec, DataRow } from "@/types/spec";

export type TableData = Record<string, DataRow[]>;

/** Poll /api/data for all records every 2s. */
export function useData(records: RecordSpec[] | undefined): TableData {
  const [data, setData] = useState<TableData>({});

  const fetchAll = useCallback(async () => {
    if (!records?.length) return;
    const next: TableData = {};
    for (const rec of records) {
      try {
        const res = await fetch(`/api/data/${rec.table}`);
        next[rec.table] = await res.json();
      } catch {
        next[rec.table] = data[rec.table] || [];
      }
    }
    setData(next);
  }, [records]);

  useEffect(() => {
    fetchAll();
    const id = setInterval(fetchAll, 2000);
    return () => clearInterval(id);
  }, [fetchAll]);

  return data;
}

/** CRUD helpers. */
export async function createRecord(table: string, row: Record<string, unknown>): Promise<DataRow> {
  const res = await fetch(`/api/data/${table}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(row),
  });
  return res.json();
}

export async function updateRecord(table: string, id: string, changes: Record<string, unknown>): Promise<void> {
  await fetch(`/api/data/${table}/${id}`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(changes),
  });
}

export async function deleteRecord(table: string, id: string): Promise<void> {
  await fetch(`/api/data/${table}/${id}`, { method: "DELETE" });
}
