<?php

namespace App\Domain\Scheduling\Listeners;

use App\Domain\Attendance\Models\AttendanceRecord;
use App\Domain\Scheduling\Events\AssignmentEnded;
use App\Domain\Training\Models\TrainingGroup;
use App\Domain\Training\Models\TrainingSession;
use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class RemoveTrainerAttendance implements ShouldQueue
{
    public function handle(AssignmentEnded $event): void
    {
        try {
            $assignment = $event->assignment;

            // Determine which sessions to clean up
            if ($assignment->assignable_type === TrainingGroup::class) {
                $futureSessionIds = TrainingSession::where('training_group_id', $assignment->assignable_id)
                    ->where('session_date', '>', today())
                    ->pluck('id');
            } elseif ($assignment->assignable_type === TrainingSession::class) {
                $session = TrainingSession::find($assignment->assignable_id);
                if (!$session || $session->session_date <= today()) {
                    return;
                }
                $futureSessionIds = collect([$session->id]);
            } else {
                return;
            }

            if ($futureSessionIds->isEmpty()) {
                return;
            }

            // Delete only 'expected' records for future sessions — don't touch past records
            AttendanceRecord::whereIn('training_session_id', $futureSessionIds)
                ->where('subject_type', User::class)
                ->where('subject_id', $assignment->user_id)
                ->where('status', 'expected')
                ->delete();
        } catch (\Throwable $e) {
            Log::error('RemoveTrainerAttendance failed: ' . $e->getMessage(), [
                'assignment_id' => $event->assignment->id,
            ]);
        }
    }

    public function failed(AssignmentEnded $event, \Throwable $exception): void
    {
        Log::critical('RemoveTrainerAttendance PERMANENTLY FAILED', [
            'assignment_id' => $event->assignment->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
