'use server'

import { createClient } from '@/utils/supabase/server'
import { revalidatePath } from 'next/cache'

export interface WorkoutGenerationParams {
  focus: string; // e.g., 'Emagrecimento', 'Força', 'Mobilidade'
  limitation?: string; // e.g., 'Dor no joelho', 'Hipertensão'
  duration: number; // in minutes, e.g., 30, 45, 60
  intensity: 'Leve' | 'Moderado' | 'Intenso';
  environment: 'Casa' | 'Academia' | 'Ar Livre';
}

export async function generateWorkout(params: WorkoutGenerationParams) {
  const supabase = await createClient()

  // 1. Get current user
  const { data: { user } } = await supabase.auth.getUser()
  if (!user) {
    throw new Error('Not authenticated')
  }

  // 2. Mock AI Logic (Placeholder for OpenAI Integration)
  // In a real scenario, we'd use process.env.OPENAI_API_KEY and call the OpenAI API
  // with a prompt tailored to `params`.
  
  const mockExercises = [
    { title: 'Aquecimento Articular', reps: '2 min', type: 'Aquecimento' },
    { title: 'Agachamento na Cadeira', reps: '3x10', type: 'Força' },
    { title: 'Flexão na Parede', reps: '3x12', type: 'Força' },
    { title: 'Caminhada no Lugar', reps: '5 min', type: 'Cardio' },
    { title: 'Alongamento Completo', reps: '3 min', type: 'Resfriamento' },
  ];

  // Tailor logic slightly based on params (mock behavior)
  let generatedExercises = [...mockExercises];
  if (params.focus === 'Mobilidade') {
    generatedExercises = [
      { title: 'Rotação de Tronco', reps: '10 cada lado', type: 'Aquecimento' },
      { title: 'Alongamento de Gato-Vaca', reps: '2 min', type: 'Mobilidade' },
      { title: 'Extensão de Pernas Sentado', reps: '3x15', type: 'Força' },
      { title: 'Caminhada Suave', reps: '5 min', type: 'Cardio' },
    ];
  }

  const workoutPayload = {
    title: `Treino de ${params.focus} (${params.duration} min)`,
    description: `Treino ${params.intensity.toLowerCase()} para fazer em ${params.environment.toLowerCase()} sem agravos.`,
    exercises: generatedExercises,
    duration: params.duration,
    intensity: params.intensity,
  }

  // 3. Save to Supabase (assuming 'treinos' table or 'historico_treinos')
  // We'll save this directly to historico_treinos as a planned or completed workout later.
  // For now, let's just insert it into a 'treinos' table or return it to the client to render.
  
  try {
    const { data: newWorkout, error } = await supabase
      .from('treinos')
      .insert({
        user_id: user.id,
        titulo: workoutPayload.title,
        descricao: workoutPayload.description,
        foco: params.focus,
        duracao_minutos: params.duration,
        intensidade: params.intensity,
        conteudo_json: workoutPayload.exercises, // assuming JSON or JSONB column
        data_criacao: new Date().toISOString()
      })
      .select()
      .single()

    if (error) {
      console.error('Save generated workout error', error)
      // Return the mock payload anyway so UI doesn't break
      return { success: true, workout: workoutPayload }
    }

    revalidatePath('/dashboard')
    revalidatePath('/workout')
    return { success: true, workout: newWorkout }
  } catch (error) {
      console.warn("Table 'treinos' might not exist or schema differs. Returning mock data.", error);
      return { success: true, workout: workoutPayload, warning: "Saved locally only (DB missing)" };
  }
}
