<?php

namespace App\Jobs;

use App\Models\User;
use App\Services\CarryOverService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;

class CarryOverJob implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new job instance.
     */
    public function __construct(
        private ?User $user = null
    ) {}

    /**
     * Execute the job.
     */
    public function handle(CarryOverService $carryOverService): void
    {
        if ($this->user) {
            // Process single user
            $carriedOver = $carryOverService->carryOverMissedSessions($this->user);
            Log::info("Carried over {$carriedOver} assignments for user {$this->user->id}");
        } else {
            // Process all users with active subscriptions
            $users = \App\Models\User::whereIn('subscription_status', ['trial', 'paid'])
                ->get();

            foreach ($users as $user) {
                if ($user->canReceiveAutomatedFeatures()) {
                    $carriedOver = $carryOverService->carryOverMissedSessions($user);
                    if ($carriedOver > 0) {
                        Log::info("Carried over {$carriedOver} assignments for user {$user->id}");
                    }
                }
            }
        }
    }
}
