<?php

namespace App\Console\Commands;

use App\Domain\Attendance\Enums\AttendanceStatus;
use App\Domain\Attendance\Models\AttendanceRecord;
use App\Domain\Training\Models\TrainingSession;
use Illuminate\Console\Command;

class MarkAutoAbsent extends Command
{
    protected $signature = 'attendance:mark-absent';
    protected $description = 'Mark expected attendance records as absent after session end + 2 hours';

    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;
        }

        $updated = AttendanceRecord::whereIn('training_session_id', $allExpiredIds)
            ->where('status', AttendanceStatus::Expected)
            ->update([
                'status' => AttendanceStatus::Absent->value,
                'is_flagged' => true,
                'marked_at' => now(),
                'metadata' => json_encode(['auto_marked' => true, 'marked_reason' => 'auto_absent_after_2h']),
            ]);

        $this->info(__('تم تسجيل :count سجل كغائب.', ['count' => $updated]));
        return self::SUCCESS;
    }
}
