import { ExerciseDef, WorkoutSet } from '../types';
import { api } from './api';

interface ApiResponse<T> {
    success: boolean;
    data: T;
    error?: string;
}

export const getExercises = async (userId: string, includeArchived: boolean = false): Promise<ExerciseDef[]> => {
    try {
        const res = await api.get<ApiResponse<ExerciseDef[]>>(`/exercises${includeArchived ? '?includeArchived=true' : ''}`);
        return res.data || [];
    } catch {
        return [];
    }
};

export const saveExercise = async (userId: string, exercise: ExerciseDef): Promise<void> => {
    await api.post<ApiResponse<any>>('/exercises', exercise);
};

export const getLastSetForExercise = async (userId: string, exerciseId: string): Promise<WorkoutSet | undefined> => {
    try {
        const response = await api.get<ApiResponse<{ set?: WorkoutSet }>>(`/exercises/${exerciseId}/last-set`);
        if (response.success && response.data?.set) {
            return response.data.set;
        }
        return undefined;
    } catch (error) {
        console.error("Failed to fetch last set:", error);
        return undefined;
    }
};
