
import api from '@/services/api';

const SERVICE_URL = '/listas_frota';

export const optionsService = {
  // Config
  getConfig: async () => {
    try {
      const response = await api.get(`${SERVICE_URL}/config`);
      // The API returns { status: { label: '...', rota: '...' }, ... }
      return response.data;
    } catch (error) {
      console.error('Error fetching options config:', error);
      throw error;
    }
  },

  // Generic fetch for a specific route
  getList: async (route) => {
    try {
      const response = await api.get(`${SERVICE_URL}/${route}`);
      // Assuming the API returns an array of strings or objects { label, value } or similar.
      // Based on the user request "seguda rota puxa todas as opições de um tipo", 
      // it likely returns a list. We'll have to handle what that list looks like.
      // For now we assume it returns { data: [...] } or just [...]
      return response.data;
    } catch (error) {
      console.error(`Error fetching list for route ${route}:`, error);
      throw error;
    }
  },

  // Helper to fetch all configured lists
  fetchAllLists: async (config) => {
    const promises = Object.values(config).map(async (item) => {
        try {
            const listData = await optionsService.getList(item.rota);
            return { key: item.rota, data: listData };
        } catch (e) {
            console.error(`Failed to fetch options for ${item.rota}`, e);
            return { key: item.rota, data: [] };
        }
    });

    const results = await Promise.all(promises);
    return results.reduce((acc, curr) => {
        acc[curr.key] = curr.data;
        return acc;
    }, {});
  }
};
