<?php

namespace App\Console\Commands;

use App\Domain\Attendance\Enums\AttendanceStatus;
use App\Domain\Attendance\Events\AttendanceMarked;
use App\Domain\Attendance\Models\AttendanceRecord;
use App\Domain\Training\Models\TrainingSession;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class AutoMarkAbsent extends Command
{
    protected $signature = 'attendance:auto-absent';
    protected $description = 'تحديد الغياب التلقائي';

    public function handle(): int
    {
        $cutoff = now()->subHours(2);

        // Only process today's and yesterday's sessions (don't touch ancient records)
        $sessionDateRange = [now()->subDay()->toDateString(), now()->toDateString()];

        // Find sessions that ended more than 2 hours ago (today or yesterday)
        $expiredSessionIds = TrainingSession::whereIn('status', ['completed', 'in_progress'])
            ->whereBetween('session_date', $sessionDateRange)
            ->whereRaw("(session_date || ' ' || end_time)::timestamp < ?", [$cutoff])
            ->pluck('id');

        if ($expiredSessionIds->isEmpty()) {
            $this->info('لا توجد سجلات تحتاج تحديث.');
            return self::SUCCESS;
        }

        // Get expected records that need to be marked absent
        $records = AttendanceRecord::whereIn('training_session_id', $expiredSessionIds)
            ->where('status', AttendanceStatus::Expected)
            ->get();

        if ($records->isEmpty()) {
            $this->info('لا توجد سجلات تحتاج تحديث.');
            return self::SUCCESS;
        }

        // Use a system user for event dispatch (first admin or fallback)
        $systemUser = User::where('email', 'admin@oc-sport.com')->first()
            ?? User::first();

        $count = 0;
        foreach ($records as $record) {
            $record->update([
                'status' => AttendanceStatus::Absent->value,
                'is_flagged' => true,
                'marked_at' => now(),
                'metadata' => json_encode([
                    'auto_marked' => true,
                    'marked_reason' => 'auto_absent_after_2h',
                ]),
            ]);

            // Dispatch event so compensation penalties and notifications fire
            if ($systemUser) {
                AttendanceMarked::dispatch($record->fresh(), $systemUser);
            }

            $count++;
        }

        $this->info("تم تسجيل {$count} سجل كغائب تلقائياً.");
        Log::info("AutoMarkAbsent: Marked {$count} records as absent");

        return self::SUCCESS;
    }
}
