import { apiClient } from "./client"; import { API_ENDPOINTS } from "../config/api"; import { isAxiosError } from "axios"; export interface Attendance { id: string; checkInTime: string; checkOutTime?: string; type: string; notes?: string; } export interface AttendanceLocationPayload { latitude: number; longitude: number; accuracy: number; } export const attendanceApi = { getHistory: async (token: string): Promise => { try { const response = await apiClient.get(API_ENDPOINTS.ATTENDANCE.HISTORY, { headers: { Authorization: `Bearer ${token}` }, }); return response.data; } catch (error) { throw new Error( getAttendanceErrorMessage(error, "Failed to load attendance history."), ); } }, checkIn: async ( type: string, token: string, location: AttendanceLocationPayload, fallbackRequested = false, ): Promise => { try { await apiClient.post( API_ENDPOINTS.ATTENDANCE.CHECK_IN, { type, location, fallbackRequested }, { headers: { Authorization: `Bearer ${token}` } }, ); } catch (error) { throw new Error( getAttendanceErrorMessage(error, "Failed to start workout."), ); } }, checkOut: async ( token: string, location: AttendanceLocationPayload, fallbackRequested = false, ): Promise => { try { await apiClient.post( API_ENDPOINTS.ATTENDANCE.CHECK_OUT, { location, fallbackRequested }, { headers: { Authorization: `Bearer ${token}` } }, ); } catch (error) { throw new Error( getAttendanceErrorMessage(error, "Failed to end workout."), ); } }, }; function getAttendanceErrorMessage(error: unknown, fallback: string): string { if (isAxiosError(error)) { const payload = error.response?.data; if (typeof payload === "string" && payload.trim()) { return payload; } if (payload && typeof payload === "object") { const message = (payload as { error?: unknown }).error; if (typeof message === "string" && message.trim()) { return message; } } } return fallback; }