/**
 * 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,
  workspaceId?: string
): 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, workspaceId);
}

/**
 * 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, workspaceId?: string): Promise<Domain> {
  return apiPost<Domain>("/api/domains", data, workspaceId);
}

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

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