import { apiClient } from '@/lib/api-client';
import type {
  AssignLeadResult,
  CreateLeadFollowupInput,
  CreateLeadInput,
  LeadDetailResponse,
  LeadListFilters,
  LeadListResponse,
  LeadMutationSuccessResponse,
  UpdateLeadInput
} from './types';

export async function getLeads(filters: LeadListFilters): Promise<LeadListResponse> {
  const searchParams = new URLSearchParams();

  if (filters.page) searchParams.set('page', String(filters.page));
  if (filters.limit) searchParams.set('limit', String(filters.limit));
  if (filters.search) searchParams.set('search', filters.search);
  if (filters.branchId) searchParams.set('branchId', filters.branchId);
  if (filters.customerId) searchParams.set('customerId', filters.customerId);
  if (filters.status) searchParams.set('status', filters.status);
  if (filters.awarenessId) searchParams.set('awarenessId', filters.awarenessId);
  if (filters.followupStatus) searchParams.set('followupStatus', filters.followupStatus);
  if (filters.outcome) searchParams.set('outcome', filters.outcome);
  if (filters.ownerMarketingUserId) {
    searchParams.set('ownerMarketingUserId', filters.ownerMarketingUserId);
  }
  if (filters.sort) searchParams.set('sort', filters.sort);

  const query = searchParams.toString();
  return apiClient<LeadListResponse>(`/crm/leads${query ? `?${query}` : ''}`);
}

export async function getLeadById(id: string): Promise<LeadDetailResponse> {
  return apiClient<LeadDetailResponse>(`/crm/leads/${id}`);
}

export async function createLead(data: CreateLeadInput): Promise<LeadMutationSuccessResponse> {
  return apiClient<LeadMutationSuccessResponse>('/crm/leads', {
    method: 'POST',
    body: JSON.stringify(data)
  });
}

export async function updateLead(
  id: string,
  data: UpdateLeadInput
): Promise<LeadMutationSuccessResponse> {
  return apiClient<LeadMutationSuccessResponse>(`/crm/leads/${id}`, {
    method: 'PATCH',
    body: JSON.stringify(data)
  });
}

export async function deleteLead(id: string): Promise<LeadMutationSuccessResponse> {
  return apiClient<LeadMutationSuccessResponse>(`/crm/leads/${id}`, {
    method: 'DELETE'
  });
}

export async function createLeadFollowup(
  leadId: string,
  data: CreateLeadFollowupInput
): Promise<LeadMutationSuccessResponse> {
  return apiClient<LeadMutationSuccessResponse>(`/crm/leads/${leadId}/followups`, {
    method: 'POST',
    body: JSON.stringify(data)
  });
}

export async function assignLead(
  leadId: string,
  data: { salesOwnerId: string; assignmentRemark?: string | null }
): Promise<AssignLeadResult> {
  return apiClient<AssignLeadResult>(`/crm/leads/${leadId}/assign`, {
    method: 'POST',
    body: JSON.stringify(data)
  });
}
