import { apiRequest } from './api';
import { loadCrmOptions } from './options';

export interface ServiceRecord {
  id: string;
  tenantId: string;
  name: string;
  description: string | null;
  isActive: boolean;
  /** Number of leads using this service; a used service can only be switched off, not deleted. */
  leadCount: number;
  createdAt: string;
  updatedAt: string;
}

export interface CreateServiceInput {
  name: string;
  description?: string | null;
  isActive?: boolean;
}

export interface UpdateServiceInput {
  name?: string;
  description?: string | null;
  isActive?: boolean;
}

export interface ListServicesQuery {
  activeOnly?: boolean;
  search?: string;
}

export const servicesApi = {
  list: (query?: ListServicesQuery) => {
    const params = new URLSearchParams();
    if (query?.activeOnly) params.set('activeOnly', 'true');
    if (query?.search?.trim()) params.set('search', query.search.trim());
    const qs = params.toString() ? `?${params.toString()}` : '';
    return apiRequest<ServiceRecord[]>(`/services${qs}`);
  },
  create: (input: CreateServiceInput) => apiRequest<ServiceRecord>('/services', { method: 'POST', body: JSON.stringify(input) }),
  update: (id: string, input: UpdateServiceInput) => apiRequest<ServiceRecord>(`/services/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify(input) }),
  toggleActive: (id: string) => apiRequest<ServiceRecord>(`/services/${encodeURIComponent(id)}/toggle`, { method: 'PATCH' }),
  remove: (id: string) => apiRequest<{ id: string }>(`/services/${encodeURIComponent(id)}`, { method: 'DELETE' }),
};

/** Service names a lead may pick: active services, or the API's built-in list when none exist; the lead's current value is always kept. */
export async function leadServiceOptions(current?: string | null): Promise<string[]> {
  const all = await servicesApi.list();
  const names = all.length === 0 ? [...(await loadCrmOptions()).defaultServices] : all.filter((r) => r.isActive).map((r) => r.name);
  if (current && !names.includes(current)) names.push(current);
  return names;
}
