<?php

namespace App\Console\Commands;

use App\Domain\Attendance\Models\AttendanceRecord;
use App\Domain\Training\Models\Enrollment;
use App\Domain\Training\Models\TrainingSession;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class BackfillAttendanceRecords extends Command
{
    protected $signature = 'attendance:backfill {--group= : Specific group ID to backfill}';
    protected $description = 'Generate missing attendance records for all active enrollments and scheduled sessions';

    public function handle(): int
    {
        $groupFilter = $this->option('group');

        $query = TrainingSession::query()
            ->whereIn('status', ['scheduled', 'in_progress']);

        if ($groupFilter) {
            $query->where('training_group_id', $groupFilter);
        }

        $sessions = $query->get();
        $inserted = 0;
        $subjectType = \App\Domain\Participant\Models\Participant::class;

        foreach ($sessions as $session) {
            $enrollments = Enrollment::where('training_group_id', $session->training_group_id)
                ->where('status', 'active')
                ->where('enrollment_date', '<=', $session->session_date)
                ->get();

            foreach ($enrollments as $enrollment) {
                $exists = AttendanceRecord::where('training_session_id', $session->id)
                    ->where('subject_type', $subjectType)
                    ->where('subject_id', $enrollment->participant_id)
                    ->exists();

                if (!$exists) {
                    AttendanceRecord::create([
                        'academy_id' => $session->academy_id,
                        'training_session_id' => $session->id,
                        'subject_type' => $subjectType,
                        'subject_id' => $enrollment->participant_id,
                        'status' => 'expected',
                        'is_auto_generated' => true,
                    ]);
                    $inserted++;
                }
            }
        }

        if ($inserted > 0) {
            $this->info("Backfilled {$inserted} missing attendance records.");
        } else {
            $this->info("No missing attendance records found.");
        }

        return self::SUCCESS;
    }
}
