import { isRecord, serverRequest } from "./serverConnection";

export interface WebDraft<TPayload = unknown> {
  id: string;
  scope: string;
  targetId: string;
  payload: TPayload;
  createdAt: string;
  updatedAt: string;
}

function toStringValue(value: unknown, fallback = ""): string {
  if (typeof value === "string") return value.trim() || fallback;
  if (typeof value === "number" && Number.isFinite(value)) return String(value);
  return fallback;
}

function normalizeDraft(raw: unknown): WebDraft {
  const item = isRecord(raw) ? raw : {};
  return {
    id: toStringValue(item.id, `draft-${Date.now()}`),
    scope: toStringValue(item.scope),
    targetId: toStringValue(item.targetId ?? item.target_id, "default"),
    payload: item.payload,
    createdAt: toStringValue(item.createdAt ?? item.created_at),
    updatedAt: toStringValue(item.updatedAt ?? item.updated_at),
  };
}

function extractDrafts(payload: unknown): WebDraft[] {
  if (Array.isArray(payload)) return payload.map(normalizeDraft);
  if (!isRecord(payload)) return [];
  const rows = payload.drafts ?? payload.items;
  return Array.isArray(rows) ? rows.map(normalizeDraft) : [];
}

export const draftClient = {
  async list(params?: { scope?: string; targetId?: string }): Promise<WebDraft[]> {
    const search = new URLSearchParams();
    if (params?.scope) search.set("scope", params.scope);
    if (params?.targetId) search.set("targetId", params.targetId);
    const query = search.toString();
    return extractDrafts(await serverRequest<unknown>(`drafts${query ? `?${query}` : ""}`));
  },

  async save<TPayload>(input: { scope: string; targetId?: string; payload: TPayload }): Promise<WebDraft<TPayload>> {
    const payload = await serverRequest<{ draft: unknown }>("drafts", {
      method: "PUT",
      body: input,
    });
    return normalizeDraft(payload.draft ?? payload) as WebDraft<TPayload>;
  },
};
