<?php

namespace Tests\Tenant;

use App\Jobs\VerifyRedirects;
use Illuminate\Support\Facades\Http;
use Mtc\MercuryDataModels\SeoRedirect;
use Tests\TenantTestCase;

class VerifyRedirectsJobTest extends TenantTestCase
{
    public function testVerifiesSuccessfulRedirect()
    {
        $redirect = SeoRedirect::factory()->create([
            'from' => '/old-page',
            'to' => '/new-page',
            'verified' => null,
        ]);

        Http::fake([
            '*' => Http::response('OK', 200, ['X-Effective-Uri' => '/new-page']),
        ]);

        // Mock the effectiveUri method
        Http::fake(function ($request) use ($redirect) {
            $response = Http::response('OK', 200);
            return $response;
        });

        (new VerifyRedirects())->handle();

        // The job should process without error
        $this->assertNotNull($redirect->fresh());
    }

    public function testProcessesUnverifiedRedirects()
    {
        SeoRedirect::factory()->create([
            'from' => '/page-1',
            'to' => '/destination-1',
            'verified' => null,
        ]);

        SeoRedirect::factory()->create([
            'from' => '/page-2',
            'to' => '/destination-2',
            'verified' => 0,
        ]);

        SeoRedirect::factory()->create([
            'from' => '/page-3',
            'to' => '/destination-3',
            'verified' => 1,
        ]);

        Http::fake([
            '*' => Http::response('OK', 200),
        ]);

        (new VerifyRedirects())->handle();

        // All redirects should still exist after processing
        $this->assertEquals(3, SeoRedirect::count());
    }

    public function testMarksRedirectAsFailedOnNon200Response()
    {
        $redirect = SeoRedirect::factory()->create([
            'from' => '/broken-page',
            'to' => '/destination',
            'verified' => null,
        ]);

        Http::fake([
            '*' => Http::response('Not Found', 404),
        ]);

        (new VerifyRedirects())->handle();

        $this->assertEquals(0, $redirect->fresh()->verified);
    }
}
