<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use App\Models\InstallRequest;
use App\Models\User;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Notifications\TelegramRequestAssignedNotification;

class AssignInstallRequest implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public InstallRequest $request;

    /**
     * Create a new job instance.
     */
    public function __construct(InstallRequest $request)
    {
        $this->request = $request;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $installer = User::where('role', 'installer')
            ->withCount(['assignedRequests' => function ($q) {
                $q->whereIn('status', ['assigned', 'in_progress']);
            }])
            ->orderBy('assigned_requests_count')
            ->orderByDesc('rating')
            ->first();

        if ($installer) {
            $this->request->update([
                'assigned_to' => $installer->id,
                'status' => 'assigned',
            ]);

            $this->request->actions()->create([
                'user_id' => $installer->id,
                'action' => 'auto-assigned',
                'comment' => 'Назначено автоматически',
            ]);

            $installer->notify(new TelegramRequestAssignedNotification($this->request));
        }
    }
}
