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

// Define the shape of session coming from API (Prisma include)
interface ApiSession extends Omit<WorkoutSession, 'startTime' | 'endTime' | 'sets'> {
    startTime: string | number; // JSON dates are strings
    endTime?: string | number;
    sets: (Omit<WorkoutSet, 'exerciseName' | 'type'> & {
        exercise?: {
            name: string;
            type: ExerciseType;
        };
        exerciseName?: string;
        type?: ExerciseType;
    })[];
}

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

export const getSessions = async (userId: string): Promise<WorkoutSession[]> => {
    try {
        const response = await api.get<ApiResponse<ApiSession[]>>('/sessions');
        const sessions = response.data || [];
        // Convert ISO date strings to timestamps
        return sessions.map((session) => ({
            ...session,
            startTime: new Date(session.startTime).getTime(),
            endTime: session.endTime ? new Date(session.endTime).getTime() : undefined,
            sets: session.sets.map((set) => ({
                ...set,
                timestamp: new Date(set.timestamp).getTime(),
                exerciseName: set.exerciseName || set.exercise?.name || 'Unknown',
                type: set.type || set.exercise?.type || ExerciseType.STRENGTH
            })) as WorkoutSet[]
        }));
    } catch {
        return [];
    }
};

export const saveSession = async (userId: string, session: WorkoutSession): Promise<void> => {
    await api.post<ApiResponse<any>>('/sessions', session);
};

export const getActiveSession = async (userId: string): Promise<WorkoutSession | null> => {
    try {
        const response = await api.get<ApiResponse<{ session: ApiSession | null }>>('/sessions/active');

        if (!response.success || !response.data?.session) {
            return null;
        }
        const session = response.data.session;
        // Convert ISO date strings to timestamps
        return {
            ...session,
            startTime: new Date(session.startTime).getTime(),
            endTime: session.endTime ? new Date(session.endTime).getTime() : undefined,
            sets: session.sets.map((set) => ({
                ...set,
                timestamp: new Date(set.timestamp).getTime(),
                exerciseName: set.exerciseName || set.exercise?.name || 'Unknown',
                type: set.type || set.exercise?.type || ExerciseType.STRENGTH
            })) as WorkoutSet[]
        };
    } catch {
        return null;
    }
};

export const updateActiveSession = async (userId: string, session: WorkoutSession): Promise<void> => {
    await api.put<ApiResponse<any>>('/sessions/active', session);
};

export const deleteSetFromActiveSession = async (userId: string, setId: string): Promise<void> => {
    await api.delete<ApiResponse<any>>(`/sessions/active/set/${setId}`);
};

export const updateSetInActiveSession = async (userId: string, setId: string, setData: Partial<WorkoutSet>): Promise<WorkoutSet> => {
    const response = await api.put<ApiResponse<{ updatedSet: ApiSession['sets'][0] }>>(`/sessions/active/set/${setId}`, setData);
    const updatedSet = response.data.updatedSet;
    return {
        ...updatedSet,
        exerciseName: updatedSet.exercise?.name || 'Unknown',
        type: updatedSet.exercise?.type || ExerciseType.STRENGTH
    } as WorkoutSet;
};

export const deleteActiveSession = async (userId: string): Promise<void> => {
    await api.delete<ApiResponse<any>>('/sessions/active');
};

export const deleteSession = async (userId: string, id: string): Promise<void> => {
    await api.delete<ApiResponse<any>>(`/sessions/${id}`);
};


export const addSetToActiveSession = async (userId: string, setData: any): Promise<any> => {
    const response = await api.post<ApiResponse<any>>('/sessions/active/log-set', setData);
    return response.data;
};

export const deleteAllUserData = (userId: string) => {
    // Not implemented in frontend
};
