<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\SelfPaced\Course;
use App\Models\SelfPaced\Enrollment;
use App\Models\User;
use Illuminate\Support\Carbon;

/**
 * SelfPacedEnrollmentSeeder
 *
 * Seeds sample enrollments with various statuses for testing.
 * Creates enrollments for existing Trainee users across all 3 sample courses.
 * Depends on SelfPacedCourseSeeder and SelfPacedTraineeSeeder having run first.
 *
 * Requirements: 15.5
 */
class SelfPacedEnrollmentSeeder extends Seeder
{
    public function run(): void
    {
        $courses = Course::whereIn('slug', [
            'community-health-promotion-disease-prevention',
            'health-sector-leadership-management',
            'health-communication-community-engagement',
        ])->get()->keyBy('slug');

        $trainees = User::whereHas('roles', fn ($q) => $q->where('name', 'Trainees'))
            ->limit(5)
            ->get();

        if ($trainees->isEmpty()) {
            $this->command->warn('SelfPacedEnrollmentSeeder: No Trainee users found. Run SelfPacedTraineeSeeder first.');
            return;
        }

        $admin = User::whereHas('roles', fn ($q) => $q->where('name', 'Super Manager'))->first();
        $adminId = $admin?->id ?? 1;

        $healthCourse        = $courses->get('community-health-promotion-disease-prevention');
        $leadershipCourse    = $courses->get('health-sector-leadership-management');
        $communicationCourse = $courses->get('health-communication-community-engagement');

        $enrollmentData = $this->buildEnrollmentData(
            $trainees,
            $healthCourse,
            $leadershipCourse,
            $communicationCourse,
            $adminId
        );

        foreach ($enrollmentData as $data) {
            // Skip if enrollment already exists (unique constraint: user_id + course_id)
            $exists = Enrollment::where('user_id', $data['user_id'])
                ->where('course_id', $data['course_id'])
                ->exists();

            if (!$exists) {
                Enrollment::create($data);
            }
        }

        $this->command->info('SelfPacedEnrollmentSeeder: Sample enrollments seeded.');
    }

    private function buildEnrollmentData(
        $trainees,
        $healthCourse,
        $leadershipCourse,
        $communicationCourse,
        int $adminId
    ): array {
        $data = [];
        $now  = Carbon::now();

        // Trainee 1 — active enrollment in health course (paid), completed in communication (free)
        if ($trainees->count() >= 1 && $healthCourse) {
            $data[] = [
                'user_id'           => $trainees[0]->id,
                'course_id'         => $healthCourse->id,
                'status'            => 'active',
                'payment_reference' => 'SP-ENR-SEED001',
                'payment_method'    => 'mtn_momo',
                'amount_paid'       => $healthCourse->fee_amount,
                'payment_date'      => $now->copy()->subDays(10),
                'enrolled_at'       => $now->copy()->subDays(10),
                'completed_at'      => null,
                'created_by'        => $trainees[0]->id,
                'created_at'        => $now->copy()->subDays(10),
                'updated_at'        => $now->copy()->subDays(10),
            ];
        }

        if ($trainees->count() >= 1 && $communicationCourse) {
            $data[] = [
                'user_id'           => $trainees[0]->id,
                'course_id'         => $communicationCourse->id,
                'status'            => 'completed',
                'payment_reference' => null,
                'payment_method'    => 'mtn_momo',
                'amount_paid'       => 0.00,
                'payment_date'      => null,
                'enrolled_at'       => $now->copy()->subDays(20),
                'completed_at'      => $now->copy()->subDays(5),
                'created_by'        => $trainees[0]->id,
                'created_at'        => $now->copy()->subDays(20),
                'updated_at'        => $now->copy()->subDays(5),
            ];
        }

        // Trainee 2 — pending payment in health course, active in leadership
        if ($trainees->count() >= 2 && $healthCourse) {
            $data[] = [
                'user_id'           => $trainees[1]->id,
                'course_id'         => $healthCourse->id,
                'status'            => 'pending_payment',
                'payment_reference' => 'SP-ENR-SEED002',
                'payment_method'    => 'mtn_momo',
                'amount_paid'       => $healthCourse->fee_amount,
                'payment_date'      => null,
                'enrolled_at'       => null,
                'completed_at'      => null,
                'created_by'        => $trainees[1]->id,
                'created_at'        => $now->copy()->subHours(2),
                'updated_at'        => $now->copy()->subHours(2),
            ];
        }

        if ($trainees->count() >= 2 && $leadershipCourse) {
            $data[] = [
                'user_id'           => $trainees[1]->id,
                'course_id'         => $leadershipCourse->id,
                'status'            => 'active',
                'payment_reference' => 'SP-ENR-SEED003',
                'payment_method'    => 'mtn_momo',
                'amount_paid'       => $leadershipCourse->fee_amount,
                'payment_date'      => $now->copy()->subDays(7),
                'enrolled_at'       => $now->copy()->subDays(7),
                'completed_at'      => null,
                'created_by'        => $trainees[1]->id,
                'created_at'        => $now->copy()->subDays(7),
                'updated_at'        => $now->copy()->subDays(7),
            ];
        }

        // Trainee 3 — payment failed in leadership, active in communication (free)
        if ($trainees->count() >= 3 && $leadershipCourse) {
            $data[] = [
                'user_id'           => $trainees[2]->id,
                'course_id'         => $leadershipCourse->id,
                'status'            => 'payment_failed',
                'payment_reference' => 'SP-ENR-SEED004',
                'payment_method'    => 'mtn_momo',
                'amount_paid'       => $leadershipCourse->fee_amount,
                'payment_date'      => null,
                'enrolled_at'       => null,
                'completed_at'      => null,
                'created_by'        => $trainees[2]->id,
                'created_at'        => $now->copy()->subDays(3),
                'updated_at'        => $now->copy()->subDays(3),
            ];
        }

        if ($trainees->count() >= 3 && $communicationCourse) {
            $data[] = [
                'user_id'           => $trainees[2]->id,
                'course_id'         => $communicationCourse->id,
                'status'            => 'active',
                'payment_reference' => null,
                'payment_method'    => 'mtn_momo',
                'amount_paid'       => 0.00,
                'payment_date'      => null,
                'enrolled_at'       => $now->copy()->subDays(5),
                'completed_at'      => null,
                'created_by'        => $trainees[2]->id,
                'created_at'        => $now->copy()->subDays(5),
                'updated_at'        => $now->copy()->subDays(5),
            ];
        }

        // Trainee 4 — completed health course, active leadership
        if ($trainees->count() >= 4 && $healthCourse) {
            $data[] = [
                'user_id'           => $trainees[3]->id,
                'course_id'         => $healthCourse->id,
                'status'            => 'completed',
                'payment_reference' => 'SP-ENR-SEED005',
                'payment_method'    => 'mtn_momo',
                'amount_paid'       => $healthCourse->fee_amount,
                'payment_date'      => $now->copy()->subDays(30),
                'enrolled_at'       => $now->copy()->subDays(30),
                'completed_at'      => $now->copy()->subDays(15),
                'created_by'        => $trainees[3]->id,
                'created_at'        => $now->copy()->subDays(30),
                'updated_at'        => $now->copy()->subDays(15),
            ];
        }

        if ($trainees->count() >= 4 && $leadershipCourse) {
            $data[] = [
                'user_id'           => $trainees[3]->id,
                'course_id'         => $leadershipCourse->id,
                'status'            => 'active',
                'payment_reference' => 'SP-ENR-SEED006',
                'payment_method'    => 'mtn_momo',
                'amount_paid'       => $leadershipCourse->fee_amount,
                'payment_date'      => $now->copy()->subDays(14),
                'enrolled_at'       => $now->copy()->subDays(14),
                'completed_at'      => null,
                'created_by'        => $trainees[3]->id,
                'created_at'        => $now->copy()->subDays(14),
                'updated_at'        => $now->copy()->subDays(14),
            ];
        }

        // Trainee 5 — cancelled enrollment in health, active in communication (free)
        if ($trainees->count() >= 5 && $healthCourse) {
            $data[] = [
                'user_id'           => $trainees[4]->id,
                'course_id'         => $healthCourse->id,
                'status'            => 'cancelled',
                'payment_reference' => 'SP-ENR-SEED007',
                'payment_method'    => 'mtn_momo',
                'amount_paid'       => 0.00,
                'payment_date'      => null,
                'enrolled_at'       => null,
                'completed_at'      => null,
                'created_by'        => $trainees[4]->id,
                'created_at'        => $now->copy()->subDays(8),
                'updated_at'        => $now->copy()->subDays(8),
            ];
        }

        if ($trainees->count() >= 5 && $communicationCourse) {
            $data[] = [
                'user_id'           => $trainees[4]->id,
                'course_id'         => $communicationCourse->id,
                'status'            => 'active',
                'payment_reference' => null,
                'payment_method'    => 'mtn_momo',
                'amount_paid'       => 0.00,
                'payment_date'      => null,
                'enrolled_at'       => $now->copy()->subDays(6),
                'completed_at'      => null,
                'created_by'        => $trainees[4]->id,
                'created_at'        => $now->copy()->subDays(6),
                'updated_at'        => $now->copy()->subDays(6),
            ];
        }

        return $data;
    }
}
