<?php

namespace Database\Seeders;

use App\Models\Client;
use App\Models\Plan;
use App\Models\Subscription;
use App\Models\User;
use App\Models\Wallet;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class DatabaseSeeder extends Seeder
{
    use WithoutModelEvents;

    /**
     * Seed the application's database.
     * 
     * This seeder is production-ready:
     * - Only creates users if they don't already exist
     * - Uses environment variables for credentials when available
     * - Creates minimal required data for system to function
     */
    public function run(): void
    {
        // Seed plans and settings (uses updateOrCreate, safe for production)
        $this->call([
            PlanSeeder::class,
            SettingSeeder::class,
        ]);

        // Create admin user only if no admin exists
        $this->createAdminUser();

        // Create initial coach only if no coaches exist
        $this->createInitialCoach();
    }

    /**
     * Create admin user if none exists.
     */
    private function createAdminUser(): void
    {
        // Check if any admin exists
        if (User::where('role', 'admin')->exists()) {
            $this->command->info('Admin user already exists, skipping...');
            return;
        }

        // Get credentials from environment or use secure defaults
        $adminEmail = env('ADMIN_EMAIL', 'admin@' . env('APP_DOMAIN', 'coachpro.local'));
        $adminPassword = env('ADMIN_PASSWORD', Str::random(16));
        
        $admin = User::create([
            'name' => env('ADMIN_NAME', 'Administrador'),
            'email' => $adminEmail,
            'password' => Hash::make($adminPassword),
            'role' => 'admin',
            'status' => 'active',
            'email_verified_at' => now(),
        ]);

        $this->command->info('');
        $this->command->info('========================================');
        $this->command->info('  ADMIN USER CREATED');
        $this->command->info('========================================');
        $this->command->info("  Email: {$adminEmail}");
        
        // Only show password if it was auto-generated
        if (!env('ADMIN_PASSWORD')) {
            $this->command->warn("  Password: {$adminPassword}");
            $this->command->warn('  ⚠️  Save this password! It won\'t be shown again.');
        } else {
            $this->command->info('  Password: (from ADMIN_PASSWORD env variable)');
        }
        $this->command->info('========================================');
        $this->command->info('');
    }

    /**
     * Create initial coach with subscription and sample client.
     */
    private function createInitialCoach(): void
    {
        // Check if any coach exists
        if (User::where('role', 'coach')->exists()) {
            $this->command->info('Coach user(s) already exist, skipping...');
            return;
        }

        // Get credentials from environment or use secure defaults
        $coachEmail = env('COACH_EMAIL', 'coach@' . env('APP_DOMAIN', 'coachpro.local'));
        $coachPassword = env('COACH_PASSWORD', Str::random(16));
        
        $coach = User::create([
            'name' => env('COACH_NAME', 'Coach Principal'),
            'email' => $coachEmail,
            'password' => Hash::make($coachPassword),
            'role' => 'coach',
            'status' => 'active',
            'email_verified_at' => now(),
            'referral_code' => strtoupper(Str::random(8)),
        ]);

        // Create wallet for coach
        Wallet::create([
            'user_id' => $coach->id,
            'balance' => 0,
        ]);

        // Assign Premium plan (for initial coach to have full access)
        $premiumPlan = Plan::where('slug', 'premium')->first();
        if ($premiumPlan) {
            Subscription::create([
                'user_id' => $coach->id,
                'plan_id' => $premiumPlan->id,
                'start_date' => now(),
                'end_date' => now()->addYear(), // 1 year for initial coach
                'status' => 'active',
            ]);
        }

        // Create initial client for the coach
        $client = $this->createInitialClient($coach);

        $this->command->info('');
        $this->command->info('========================================');
        $this->command->info('  COACH USER CREATED');
        $this->command->info('========================================');
        $this->command->info("  Email: {$coachEmail}");
        
        if (!env('COACH_PASSWORD')) {
            $this->command->warn("  Password: {$coachPassword}");
            $this->command->warn('  ⚠️  Save this password! It won\'t be shown again.');
        } else {
            $this->command->info('  Password: (from COACH_PASSWORD env variable)');
        }
        
        $this->command->info("  Plan: Premium (1 year)");
        $this->command->info("  Client created: {$client->name}");
        $this->command->info('========================================');
        $this->command->info('');
    }

    /**
     * Create an initial client for the coach.
     */
    private function createInitialClient(User $coach): Client
    {
        // Create client profile
        $client = Client::create([
            'user_id' => $coach->id,
            'name' => env('CLIENT_NAME', 'Cliente Inicial'),
            'email' => env('CLIENT_EMAIL', 'cliente@' . env('APP_DOMAIN', 'coachpro.local')),
            'phone' => null,
            'age' => null,
            'weight' => null,
            'height' => null,
            'gender' => null,
            'objective' => 'maintain',
            'activity_level' => 'moderate',
            'notes' => 'Cliente inicial del sistema. Complete los datos del perfil.',
            'is_active' => true,
        ]);

        // Optionally create portal access for client
        if (env('CREATE_CLIENT_PORTAL_ACCESS', false)) {
            $clientPassword = env('CLIENT_PASSWORD', Str::random(16));
            
            $clientUser = User::create([
                'name' => $client->name,
                'email' => $client->email,
                'password' => Hash::make($clientPassword),
                'role' => 'client',
                'status' => 'active',
                'email_verified_at' => now(),
            ]);

            $client->update(['client_user_id' => $clientUser->id]);

            $this->command->info('');
            $this->command->info('  CLIENT PORTAL ACCESS CREATED');
            $this->command->info("  Email: {$client->email}");
            
            if (!env('CLIENT_PASSWORD')) {
                $this->command->warn("  Password: {$clientPassword}");
            }
        }

        return $client;
    }
}
