<?php

namespace Tests\Feature;

use Mtc\MercuryDataModels\Page;
use Mtc\MercuryDataModels\SeoRedirect;
use Tests\DatabaseTestCase;

class SeoRedirectMiddlewareTest extends DatabaseTestCase
{
    public function testSeoRedirects()
    {
        Page::factory()->create(['slug' => 'aboutus', 'status' => 'published']);
        $response = $this->asTenant(tenant())
            ->withHeader('x-path', '/aboutus')
            ->getJson(route('pages.show', 'aboutus'));
        $response->assertStatus(200);

        SeoRedirect::factory()->create([
            'from' => '/aboutus',
            'to' => '/about-us',
            'code' => 301,
            'from_domain' => '',
            'to_domain' => '',
        ]);

        $response = $this->asTenant(tenant())
            ->withHeader('x-path', '/aboutus')
            ->getJson(route('pages.show', 'aboutus'));
        $response->assertStatus(404);
        $this->assertEquals(301, $response->json('code'));
        $this->assertEquals('redirect', $response->json('type'));
        $this->assertEquals('/about-us', $response->json('to'));
    }

    public function testSeoGoneReturnsHttp410()
    {
        Page::factory()->create(['slug' => 'old-product', 'status' => 'published']);

        SeoRedirect::factory()->create([
            'from' => '/old-product',
            'to' => null,
            'code' => 410,
            'from_domain' => '',
            'to_domain' => '',
        ]);

        $response = $this->asTenant(tenant())
            ->withHeader('x-path', '/old-product')
            ->getJson(route('pages.show', 'old-product'));

        $response->assertStatus(410);
        $this->assertEquals(410, $response->json('code'));
        $this->assertEquals('gone', $response->json('type'));
        $this->assertNull($response->json('to'));
    }
}
