<?php

namespace App\Jobs;

use App\Enums\ContestStatusEnum;
use App\Enums\NotificationType;
use App\Models\Contest;
use App\Notifications\UserAutoNotification;
use App\Services\Contest\ContestWinnerService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Notification;

class ContestChangeStatusJob implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new job instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $this->changeStatusToRunning();
        $this->changeStatusToCompleted();
    }

    private function changeStatusToRunning(): void
    {
        $contests = Contest::upcoming()
            ->where('start_time', '<=', now())
            ->get();

        foreach ($contests as $contest) {
            $contest->status = ContestStatusEnum::RUNNING; // assuming you want to update the status too
            $contest->save();

            foreach ($contest->participants as $participant) {
                $user = $participant->user;

                Notification::sendNow($user, new UserAutoNotification(NotificationType::CONTEST_STARTED));
            }
        }
    }

    private function changeStatusToCompleted(): void
    {
        $contests = Contest::running()
            ->where('end_time', '<=', now())
            ->get();

        foreach ($contests as $contest) {
            foreach ($contest->participants as $participant) {
                $user = $participant->user;

                Notification::sendNow($user, new UserAutoNotification(NotificationType::CONTEST_ENDED));
            }
            // Determine the winner
            $winner_service = new ContestWinnerService;

            $winner_service->determineWinner($contest);

        }
    }
}
