// lib/api/platforms.ts
export type Platform = {
  id: number;
  key: string;
  label: string;
  isActive: boolean;
};

export type CreatePlatformDto = {
  key: string;
  label: string;
  isActive?: boolean;
};

export type UpdatePlatformDto = Partial<CreatePlatformDto>;

function normalizePlatform(raw: any): Platform {
  const id = Number(raw?.id);
  const key = String(raw?.key ?? "").trim();
  const label = String(raw?.label ?? "").trim();

  const activeRaw = raw?.isActive ?? raw?.is_active ?? true;
  const isActive =
    typeof activeRaw === "boolean"
      ? activeRaw
      : typeof activeRaw === "number"
        ? activeRaw === 1
        : String(activeRaw).toLowerCase() === "true";

  return { id, key, label, isActive };
}

export async function fetchPlatforms(_tokenHeaders: HeadersInit): Promise<Platform[]> {
  const res = await fetch('/api/admin/platforms', {
    credentials: 'include',
  });

  if (!res.ok) {
    throw new Error(`Failed to load platforms (${res.status})`);
  }

  const data = (await res.json()) as unknown;
  const items = Array.isArray(data) ? data : [];
  return items.map(normalizePlatform).filter((p) => Number.isFinite(p.id) && p.key && p.label);
}

export async function createPlatform(
  _tokenHeaders: HeadersInit,
  dto: CreatePlatformDto
): Promise<Platform> {
  const res = await fetch('/api/admin/platforms', {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    credentials: 'include',
    body: JSON.stringify(dto),
  });

  if (!res.ok) {
    const text = await res.text().catch(() => "");
    throw new Error(text || `Failed to create platform (${res.status})`);
  }

  return normalizePlatform(await res.json());
}

export async function updatePlatform(
  _tokenHeaders: HeadersInit,
  id: number,
  dto: UpdatePlatformDto
): Promise<Platform> {
  const res = await fetch(`/api/admin/platforms/${id}`, {
    method: "PATCH",
    headers: {
      "Content-Type": "application/json",
    },
    credentials: 'include',
    body: JSON.stringify(dto),
  });

  if (!res.ok) {
    const text = await res.text().catch(() => "");
    throw new Error(text || `Failed to update platform (${res.status})`);
  }

  return normalizePlatform(await res.json());
}

export async function deletePlatform(_tokenHeaders: HeadersInit, id: number): Promise<void> {
  const res = await fetch(`/api/admin/platforms/${id}`, {
    method: "DELETE",
    credentials: 'include',
  });

  if (!res.ok) {
    const text = await res.text().catch(() => "");
    throw new Error(text || `Failed to delete platform (${res.status})`);
  }
}
