import { Attendance, DashboardFilter, User } from '../types'; // URL do Backend // Em produção (import.meta.env.PROD), usa caminho relativo '/api' pois o backend serve o frontend // Em desenvolvimento, aponta para o localhost:3001 const API_URL = import.meta.env.PROD ? '/api' : 'http://localhost:3001/api'; export const getAttendances = async (tenantId: string, filter: DashboardFilter): Promise => { try { const params = new URLSearchParams(); params.append('tenantId', tenantId); if (filter.dateRange.start) params.append('startDate', filter.dateRange.start.toISOString()); if (filter.dateRange.end) params.append('endDate', filter.dateRange.end.toISOString()); if (filter.userId && filter.userId !== 'all') params.append('userId', filter.userId); if (filter.teamId && filter.teamId !== 'all') params.append('teamId', filter.teamId); const response = await fetch(`${API_URL}/attendances?${params.toString()}`); if (!response.ok) { throw new Error('Falha ao buscar atendimentos do servidor'); } return await response.json(); } catch (error) { console.error("API Error (getAttendances):", error); // Fallback vazio ou lançar erro para a UI tratar return []; } }; export const getUsers = async (tenantId: string): Promise => { try { const params = new URLSearchParams(); if (tenantId !== 'all') params.append('tenantId', tenantId); const response = await fetch(`${API_URL}/users?${params.toString()}`); if (!response.ok) throw new Error('Falha ao buscar usuários'); return await response.json(); } catch (error) { console.error("API Error (getUsers):", error); return []; } }; export const getUserById = async (id: string): Promise => { try { const response = await fetch(`${API_URL}/users/${id}`); if (!response.ok) return undefined; const contentType = response.headers.get("content-type"); if (contentType && contentType.indexOf("application/json") !== -1) { return await response.json(); } return undefined; } catch (error) { console.error("API Error (getUserById):", error); return undefined; } }; export const updateUser = async (id: string, userData: any): Promise => { try { const response = await fetch(`${API_URL}/users/${id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(userData) }); return response.ok; } catch (error) { console.error("API Error (updateUser):", error); return false; } }; export const createMember = async (userData: any): Promise => { try { const response = await fetch(`${API_URL}/users`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(userData) }); return response.ok; } catch (error) { console.error("API Error (createMember):", error); return false; } }; export const deleteUser = async (id: string): Promise => { try { const response = await fetch(`${API_URL}/users/${id}`, { method: 'DELETE' }); return response.ok; } catch (error) { console.error("API Error (deleteUser):", error); return false; } }; export const getAttendanceById = async (id: string): Promise => { try { const response = await fetch(`${API_URL}/attendances/${id}`); if (!response.ok) return undefined; const contentType = response.headers.get("content-type"); if (contentType && contentType.indexOf("application/json") !== -1) { return await response.json(); } return undefined; } catch (error) { console.error("API Error (getAttendanceById):", error); return undefined; } }; export const getTenants = async (): Promise => { try { const response = await fetch(`${API_URL}/tenants`); if (!response.ok) throw new Error('Falha ao buscar tenants'); const contentType = response.headers.get("content-type"); if (contentType && contentType.indexOf("application/json") !== -1) { return await response.json(); } return []; } catch (error) { console.error("API Error (getTenants):", error); return []; } }; export const getTeams = async (tenantId: string): Promise => { try { const response = await fetch(`${API_URL}/teams?tenantId=${tenantId}`); if (!response.ok) throw new Error('Falha ao buscar equipes'); return await response.json(); } catch (error) { console.error("API Error (getTeams):", error); return []; } }; export const createTeam = async (teamData: any): Promise => { try { const response = await fetch(`${API_URL}/teams`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(teamData) }); return response.ok; } catch (error) { console.error("API Error (createTeam):", error); return false; } }; export const updateTeam = async (id: string, teamData: any): Promise => { try { const response = await fetch(`${API_URL}/teams/${id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(teamData) }); return response.ok; } catch (error) { console.error("API Error (updateTeam):", error); return false; } }; export const createTenant = async (tenantData: any): Promise => { try { const response = await fetch(`${API_URL}/tenants`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(tenantData) }); return response.ok; } catch (error) { console.error("API Error (createTenant):", error); return false; } }; // --- Auth Functions --- export const login = async (credentials: any): Promise => { const response = await fetch(`${API_URL}/auth/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(credentials) }); const contentType = response.headers.get("content-type"); const isJson = contentType && contentType.indexOf("application/json") !== -1; if (!response.ok) { const error = isJson ? await response.json() : { error: 'Erro no servidor' }; throw new Error(error.error || 'Erro no login'); } return isJson ? await response.json() : null; }; export const register = async (userData: any): Promise => { const response = await fetch(`${API_URL}/auth/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(userData) }); if (!response.ok) { const error = await response.json(); throw new Error(error.error || 'Erro no registro'); } return true; }; export const verifyCode = async (data: any): Promise => { const response = await fetch(`${API_URL}/auth/verify`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }); if (!response.ok) { const error = await response.json(); throw new Error(error.error || 'Código inválido ou expirado'); } return true; }; export const forgotPassword = async (email: string): Promise => { const response = await fetch(`${API_URL}/auth/forgot-password`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email }) }); const contentType = response.headers.get("content-type"); const isJson = contentType && contentType.indexOf("application/json") !== -1; if (!response.ok) { const error = isJson ? await response.json() : { error: 'Erro no servidor' }; throw new Error(error.error || 'Erro ao processar solicitação'); } const data = isJson ? await response.json() : { message: 'Solicitação processada' }; return data.message; }; export const resetPassword = async (password: string, token: string): Promise => { const response = await fetch(`${API_URL}/auth/reset-password`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ password, token }) }); const contentType = response.headers.get("content-type"); const isJson = contentType && contentType.indexOf("application/json") !== -1; if (!response.ok) { const error = isJson ? await response.json() : { error: 'Erro no servidor' }; throw new Error(error.error || 'Erro ao resetar senha'); } const data = isJson ? await response.json() : { message: 'Senha redefinida' }; return data.message; };