import { supabase } from './supabaseClient';

const normalizeTasks = (tasks) => {
  if (!Array.isArray(tasks)) return [];
  return tasks.map((task) => ({
    type: task?.type || 'task',
    title: task?.title || '',
    durationMin: Number(task?.durationMin || 0),
    repetitions: task?.repetitions ?? null,
    intensity: task?.intensity || null,
    instructions: task?.instructions || ''
  }));
};

export const mapSessionToRpc = (session) => ({
  weekNo: Number(session?.weekNo || session?.week_no || 1),
  sessionNo: Number(session?.sessionNo || session?.session_no || 1),
  mainExercise: session?.mainExercise || session?.main_exercise || 'Basistechnik',
  secondaryExercises: Array.isArray(session?.secondaryExercises)
    ? session.secondaryExercises
    : Array.isArray(session?.secondary_exercises)
      ? session.secondary_exercises
      : [],
  tasks: normalizeTasks(session?.tasks),
  state: session?.state || 'open',
  notes: session?.notes || ''
});

export const saveTrainingPlanWithSessions = async ({
  patType,
  analysisSnapshot,
  durationWeeks,
  sessionsPerWeek,
  sessions
}) => {
  if (!supabase) {
    return {
      ok: false,
      error: new Error('Supabase ist nicht konfiguriert.')
    };
  }

  try {
    const payload = {
      p_pat_type: patType,
      p_analysis_snapshot: analysisSnapshot,
      p_duration_weeks: Number(durationWeeks),
      p_sessions_per_week: Number(sessionsPerWeek),
      p_sessions: (sessions || []).map(mapSessionToRpc)
    };

    const { data, error } = await supabase.rpc('create_training_plan_with_sessions', payload);

    if (error) throw error;

    return {
      ok: true,
      planId: data
    };
  } catch (error) {
    return {
      ok: false,
      error
    };
  }
};
