/**
 * Domain API Client
 * Handles domain-related API requests
 */

import type { Domain, DomainWithCounts } from "@mosaic/shared";
import { apiGet, apiPost, apiPatch, apiDelete, type ApiResponse } from "./client";

/**
 * Create domain DTO
 */
export interface CreateDomainDto {
  name: string;
  slug: string;
  description?: string;
  color?: string;
  icon?: string;
  sortOrder?: number;
  metadata?: Record<string, unknown>;
}

/**
 * Update domain DTO
 */
export interface UpdateDomainDto {
  name?: string;
  slug?: string;
  description?: string;
  color?: string;
  icon?: string;
  sortOrder?: number;
  metadata?: Record<string, unknown>;
}

/**
 * Domain filters for querying
 */
export interface DomainFilters {
  search?: string;
  page?: number;
  limit?: number;
}

/**
 * Fetch all domains
 */
export async function fetchDomains(filters?: DomainFilters): Promise<ApiResponse<Domain[]>> {
  const params = new URLSearchParams();

  if (filters?.search) {
    params.append("search", filters.search);
  }
  if (filters?.page) {
    params.append("page", filters.page.toString());
  }
  if (filters?.limit) {
    params.append("limit", filters.limit.toString());
  }

  const queryString = params.toString();
  const endpoint = queryString ? `/api/domains?${queryString}` : "/api/domains";

  return apiGet<ApiResponse<Domain[]>>(endpoint);
}

/**
 * Fetch a single domain by ID
 */
export async function fetchDomain(id: string): Promise<DomainWithCounts> {
  return apiGet<DomainWithCounts>(`/api/domains/${id}`);
}

/**
 * Create a new domain
 */
export async function createDomain(data: CreateDomainDto): Promise<Domain> {
  return apiPost<Domain>("/api/domains", data);
}

/**
 * Update a domain
 */
export async function updateDomain(id: string, data: UpdateDomainDto): Promise<Domain> {
  return apiPatch<Domain>(`/api/domains/${id}`, data);
}

/**
 * Delete a domain
 */
export async function deleteDomain(id: string): Promise<Record<string, never>> {
  return apiDelete<Record<string, never>>(`/api/domains/${id}`);
}
