<?php

namespace App\Jobs;

use App\Facades\Site;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Mtc\MercuryDataModels\SeoRedirect;

class VerifyRedirects implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public $timeout = 0;

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

    public function middleware()
    {
        return [new WithoutOverlapping()];
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $failed = collect();
        SeoRedirect::query()
            ->whereNull('verified')
            ->orWhere('verified', 0)
            ->get()
            ->each(fn (SeoRedirect $redirect) => $this->checkRedirect($redirect, $failed));
    }

    private function checkRedirect(SeoRedirect $redirect, Collection $failed)
    {
        if ((int) $redirect->code === 410) {
            $redirect->verified = 1;
            $redirect->save();
            return;
        }
        $response = Http::get(Site::url($redirect->from));
        if ($response->status() != 200 || $response->effectiveUri()->getPath() != $redirect->to) {
            $failed->push($redirect);
            $redirect->verified = 0;
        } else {
            $redirect->verified = 1;
        }
        $redirect->save();
    }
}
