/**
 * TabataFit Seed Script
 * 
 * This script seeds your Supabase database with the initial data.
 * Run this after setting up your Supabase project.
 * 
 * Usage:
 * 1. Set your Supabase credentials in .env
 * 2. Run: npx ts-node supabase/seed.ts
 */

import { createClient } from '@supabase/supabase-js'
import { WORKOUTS } from '../src/shared/data/workouts'
import { TRAINERS } from '../src/shared/data/trainers'
import { PROGRAMS } from '../src/shared/data/programs'
import { ACHIEVEMENTS } from '../src/shared/data/achievements'

/**
 * Seed data for collections — used only for initial database seeding.
 * The app fetches collections from Supabase at runtime.
 */
const SEED_COLLECTIONS = [
  {
    id: 'morning-energizer',
    title: 'Morning Energizer',
    description: 'Start your day right',
    icon: '🌅',
    workoutIds: ['4', '6', '43', '47', '10'],
  },
  {
    id: 'no-equipment',
    title: 'No Equipment',
    description: 'Workout anywhere',
    icon: '💪',
    workoutIds: ['1', '4', '6', '11', '13', '16', '17', '19', '23', '26', '31', '38', '42', '43', '45'],
  },
  {
    id: '7-day-burn',
    title: '7-Day Burn Challenge',
    description: 'Transform in one week',
    icon: '🔥',
    workoutIds: ['1', '11', '31', '42', '6', '17', '23'],
    gradient: ['#FF6B35', '#FF3B30'],
  },
  {
    id: 'quick-intense',
    title: 'Quick & Intense',
    description: 'Max effort in 4 minutes',
    icon: '⚡',
    workoutIds: ['1', '11', '23', '35', '38', '42', '6', '17'],
  },
  {
    id: 'core-focus',
    title: 'Core Focus',
    description: 'Build a solid foundation',
    icon: '🎯',
    workoutIds: ['11', '12', '13', '14', '16', '17'],
  },
  {
    id: 'leg-day',
    title: 'Leg Day',
    description: 'Never skip leg day',
    icon: '🦵',
    workoutIds: ['31', '32', '33', '34', '35', '36', '37'],
  },
]

const supabaseUrl = process.env.EXPO_PUBLIC_SUPABASE_URL
const supabaseKey = process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY

if (!supabaseUrl || !supabaseKey) {
  console.error('Missing Supabase credentials. Please set EXPO_PUBLIC_SUPABASE_URL and EXPO_PUBLIC_SUPABASE_ANON_KEY')
  process.exit(1)
}

const supabase = createClient(supabaseUrl, supabaseKey)

async function seedTrainers() {
  console.log('Seeding trainers...')
  
  const trainers = TRAINERS.map(t => ({
    id: t.id,
    name: t.name,
    specialty: t.specialty,
    color: t.color,
    avatar_url: t.avatarUrl || null,
    workout_count: t.workoutCount,
  }))

  const { error } = await supabase.from('trainers').upsert(trainers)
  if (error) throw error
  console.log(`✅ Seeded ${trainers.length} trainers`)
}

async function seedWorkouts() {
  console.log('Seeding workouts...')
  
  const workouts = WORKOUTS.map(w => ({
    id: w.id,
    title: w.title,
    trainer_id: w.trainerId,
    category: w.category,
    level: w.level,
    duration: w.duration,
    calories: w.calories,
    rounds: w.rounds,
    prep_time: w.prepTime,
    work_time: w.workTime,
    rest_time: w.restTime,
    equipment: w.equipment,
    music_vibe: w.musicVibe,
    exercises: w.exercises,
    thumbnail_url: w.thumbnailUrl || null,
    video_url: w.videoUrl || null,
    is_featured: w.isFeatured || false,
  }))

  const { error } = await supabase.from('workouts').upsert(workouts)
  if (error) throw error
  console.log(`✅ Seeded ${workouts.length} workouts`)
}

async function seedCollections() {
  console.log('Seeding collections...')
  
  const collections = SEED_COLLECTIONS.map(c => ({
    id: c.id,
    title: c.title,
    description: c.description,
    icon: c.icon,
    gradient: c.gradient || null,
  }))

  const { error } = await supabase.from('collections').upsert(collections)
  if (error) throw error

  // Seed collection-workout relationships
  const collectionWorkouts = SEED_COLLECTIONS.flatMap(c => 
    c.workoutIds.map((workoutId, index) => ({
      collection_id: c.id,
      workout_id: workoutId,
      sort_order: index,
    }))
  )

  const { error: linkError } = await supabase.from('collection_workouts').upsert(collectionWorkouts)
  if (linkError) throw linkError

  console.log(`✅ Seeded ${collections.length} collections with ${collectionWorkouts.length} workout links`)
}

async function seedPrograms() {
  console.log('Seeding programs...')
  
  const programs = Object.values(PROGRAMS).map(p => ({
    id: p.id,
    title: p.title,
    description: p.description,
    weeks: p.weeks,
    workouts_per_week: p.workoutsPerWeek,
  }))

  const { error } = await supabase.from('programs').upsert(programs)
  if (error) throw error

  // Seed program-workout relationships
  let programWorkouts: { program_id: string; workout_id: string; week_number: number; day_number: number }[] = []

  Object.values(PROGRAMS).forEach(program => {
    program.weeks.forEach((week) => {
      week.workouts.forEach((workout, dayIndex) => {
        programWorkouts.push({
          program_id: program.id,
          workout_id: workout.id,
          week_number: week.weekNumber,
          day_number: dayIndex + 1,
        })
      })
    })
  })

  const { error: linkError } = await supabase.from('program_workouts').upsert(programWorkouts)
  if (linkError) throw linkError

  console.log(`✅ Seeded ${programs.length} programs with ${programWorkouts.length} workout links`)
}

async function seedAchievements() {
  console.log('Seeding achievements...')
  
  const achievements = ACHIEVEMENTS.map(a => ({
    id: a.id,
    title: a.title,
    description: a.description,
    icon: a.icon,
    requirement: a.requirement,
    type: a.type,
  }))

  const { error } = await supabase.from('achievements').upsert(achievements)
  if (error) throw error
  console.log(`✅ Seeded ${achievements.length} achievements`)
}

async function main() {
  try {
    console.log('🌱 Starting database seed...\n')
    
    await seedTrainers()
    await seedWorkouts()
    await seedCollections()
    await seedPrograms()
    await seedAchievements()
    
    console.log('\n✨ Database seeded successfully!')
    console.log('\nNext steps:')
    console.log('1. Set up storage buckets in Supabase Dashboard')
    console.log('2. Upload video and thumbnail files')
    console.log('3. Create an admin user in the admin_users table')
    console.log('4. Access the admin dashboard at /admin')
  } catch (error) {
    console.error('\n❌ Seeding failed:', error)
    process.exit(1)
  }
}

main()
