/**
 * Dealer API Service
 * Handles API calls for dealer-related operations
 */

import apiClient from './authApi';

export interface DealerInfo {
  userId: string;
  email: string;
  dealerCode: string;
  dealerName: string;
  displayName: string;
  phone?: string;
  department?: string;
  designation?: string;
}

/**
 * Get all dealers
 */
export async function getAllDealers(): Promise<DealerInfo[]> {
  try {
    const res = await apiClient.get('/dealers');
    return res.data?.data || res.data || [];
  } catch (error) {
    console.error('[DealerAPI] Error fetching dealers:', error);
    throw error;
  }
}

/**
 * Get dealer by code
 */
export async function getDealerByCode(dealerCode: string): Promise<DealerInfo | null> {
  try {
    const res = await apiClient.get(`/dealers/code/${dealerCode}`);
    return res.data?.data || res.data || null;
  } catch (error) {
    console.error('[DealerAPI] Error fetching dealer by code:', error);
    return null;
  }
}

/**
 * Get dealer by email
 */
export async function getDealerByEmail(email: string): Promise<DealerInfo | null> {
  try {
    const res = await apiClient.get(`/dealers/email/${encodeURIComponent(email)}`);
    return res.data?.data || res.data || null;
  } catch (error) {
    console.error('[DealerAPI] Error fetching dealer by email:', error);
    return null;
  }
}

/**
 * Search dealers
 */
export async function searchDealers(searchTerm: string): Promise<DealerInfo[]> {
  try {
    const res = await apiClient.get('/dealers/search', {
      params: { q: searchTerm },
    });
    return res.data?.data || res.data || [];
  } catch (error) {
    console.error('[DealerAPI] Error searching dealers:', error);
    return [];
  }
}

