<?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 MarkAutoAbsent extends Command
{
    protected $signature = 'attendance:mark-absent';
    protected $description = 'تحديد الغياب التلقائي بعد انتهاء الجلسة بساعتين';

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

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

        // Also check in_progress sessions past their end time + 2h
        $inProgressExpired = TrainingSession::where('status', 'in_progress')
            ->whereRaw("(session_date || ' ' || end_time)::timestamp < ?", [$cutoff])
            ->pluck('id');

        $allExpiredIds = $expiredSessionIds->merge($inProgressExpired)->unique();

        if ($allExpiredIds->isEmpty()) {
            $this->info('لا توجد جلسات منتهية.');
            return self::SUCCESS;
        }

        // Get records individually so we can dispatch events per record
        $records = AttendanceRecord::whereIn('training_session_id', $allExpiredIds)
            ->where('status', AttendanceStatus::Expected)
            ->get();

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

        $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']),
            ]);

            if ($systemUser) {
                AttendanceMarked::dispatch($record->fresh(), $systemUser);
            }

            $count++;
        }

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

        return self::SUCCESS;
    }
}
