<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Models\Session;
use App\Services\ActivityLogger;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

final class CloseSessionsJob implements ShouldQueue
{
    use Queueable;

    /**
     * Find all in-progress sessions idle for more than 12 hours and mark them as
     * 'unfinished' status, logging each closure individually via ActivityLogger.
     */
    public function handle(): void
    {
        Session::query()
            ->where('status', 'in_progress')
            ->where('created_at', '<', now()->subHours(12))
            ->each(function (Session $session): void {
                $session->update([
                    'status' => 'unfinished',
                    'completed_at' => now(),
                ]);

                ActivityLogger::log(
                    'session_auto_closed',
                    $session->user_id,
                    sessionId: $session->id,
                    categoryId: $session->category_id,
                    metadata: ['reason' => 'idle_12h'],
                );
            });
    }
}
