<?php

namespace Tests\Tenant;

use Illuminate\Http\UploadedFile;
use Mtc\MercuryDataModels\SeoData;
use Tests\TenantTestCase;
use Tests\UserForTenant;

class SeoHeadingTest extends TenantTestCase
{
    use UserForTenant;

    public function testIndexPage()
    {
        SeoData::factory(4)->create();
        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->getJson(route('tenant.seo_settings.headings.index'));

        $response->assertStatus(200);
        $this->assertCount(4, $response->json('data'));
    }

    public function testStorePage()
    {
        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->postJson(route('tenant.seo_settings.headings.store'), [
                'path' => '/foo',
                'heading' => 'foo baz bar'
            ]);

        $response->assertStatus(200);
        $seo = SeoData::query()->where('path', '/foo')->first();
        $this->assertEquals('foo baz bar', $seo->heading);
    }

    public function testUpdatePage()
    {
        $seo = SeoData::factory()->create();
        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->putJson(route('tenant.seo_settings.headings.update', $seo->id), [
                'path' => '/foo',
                'heading' => 'baz bar',
            ]);

        $response->assertStatus(200);
        $seo->refresh();
        $this->assertEquals('baz bar', $seo->heading);
    }

    public function testDeletePage()
    {
        $seo = SeoData::factory()->create();
        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->deleteJson(route('tenant.seo_settings.headings.destroy', $seo->id));

        $response->assertStatus(200);
        $exists = SeoData::query()
            ->where('id', $seo->id)
            ->whereNotNull('heading')
            ->exists();
        $this->assertFalse($exists);
    }

    public function testExport()
    {
        SeoData::factory(10)->create();
        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->postJson(route('tenant.seo_settings.headings.export'));

        $response->assertStatus(200);
        $response->assertDownload('seo_headings.xlsx');
    }

    public function testImport()
    {
        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->postJson(route('tenant.seo_settings.headings.import'), [
                'truncate' => true,
                'file' => UploadedFile::fake()->createWithContent(
                    'seo_data_import.csv',
                    file_get_contents(dirname(__DIR__) . '/data/seo_heading_import.csv')
                ),
            ]);

        $response->assertStatus(200);
        $this->assertEquals(2, SeoData::query()->count());
    }
}
