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

import apiClient from './authApi';

export interface DealerInfo {
  dealerId: string;
  userId?: string | null; // User ID if dealer is logged in
  email: string; // domain_id from dealers table
  dealerCode: string; // dlrcode from dealers table
  dealerName: string; // dealership from dealers table
  displayName: string; // dealer_principal_name from dealers table
  phone?: string; // dp_contact_number from dealers table
  department?: string;
  designation?: string;
  isLoggedIn: boolean; // Whether dealer's domain_id exists in users table
  salesCode?: string | null;
  serviceCode?: string | null;
  gearCode?: string | null;
  gmaCode?: string | null;
  region?: string | null;
  state?: string | null;
  district?: string | null;
  city?: string | null;
  dealerPrincipalName?: string | null;
  dealerPrincipalEmailId?: string | null;
  itemGroup?: string | null;
  parentCode?: string | null;
}

/**
 * Get all dealers (with optional search)
 * @param searchTerm - Optional search term to filter dealers
 * @param limit - Maximum number of records to return (default: 10)
 */
export async function getAllDealers(searchTerm?: string, limit: number = 10): Promise<DealerInfo[]> {
  try {
    const params: any = { limit };
    if (searchTerm) {
      params.q = searchTerm;
    }
    const res = await apiClient.get('/dealers', { params });
    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
 * @param searchTerm - Search term to filter dealers
 * @param limit - Maximum number of records to return (default: 10)
 */
export async function searchDealers(searchTerm: string, limit: number = 10): Promise<DealerInfo[]> {
  try {
    const res = await apiClient.get('/dealers/search', {
      params: { q: searchTerm, limit },
    });
    return res.data?.data || res.data || [];
  } catch (error) {
    console.error('[DealerAPI] Error searching dealers:', error);
    return [];
  }
}

/**
 * Verify dealer is logged in to the system
 * Throws error if dealer is not logged in
 */
export async function verifyDealerLogin(dealerCode: string): Promise<DealerInfo> {
  try {
    const res = await apiClient.get(`/dealers/verify/${dealerCode}`);
    return res.data?.data || res.data;
  } catch (error: any) {
    const errorMessage = error.response?.data?.message || error.message || 'Dealer verification failed';
    console.error('[DealerAPI] Error verifying dealer login:', errorMessage);
    throw new Error(errorMessage);
  }
}

/**
 * Search dealer by code from external Royal Enfield API
 * @param dealerCode - The code to search for
 */
export async function searchExternalDealerByCode(dealerCode: string): Promise<any | null> {
  try {
    const res = await apiClient.get(`/dealers-external/search/${dealerCode}`);
    return res.data?.data || res.data || null;
  } catch (error) {
    console.error('[DealerAPI] Error searching external dealer:', error);
    return null;
  }
}
