import { BodyWeightRecord } from '../types';
import { api } from './api';

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

export const getWeightHistory = async (): Promise<BodyWeightRecord[]> => {
    try {
        const res = await api.get<ApiResponse<BodyWeightRecord[]>>('/weight');
        return res.data || [];
    } catch (error) {
        console.error('Error fetching weight history:', error);
        return [];
    }
};

export const logWeight = async (weight: number, dateStr?: string): Promise<BodyWeightRecord | null> => {
    try {
        // Default to today if no date provided
        const date = dateStr || new Date().toISOString().split('T')[0];

        const res = await api.post<ApiResponse<BodyWeightRecord>>('/weight', { weight, dateStr: date });
        return res.data;
    } catch (error) {
        console.error('Error logging weight:', error);
        return null;
    }
};
