<?php

namespace Tests\Feature\Controllers;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
use Tests\UserForTenant;

class SiteDomainControllerTest extends TestCase
{
    use RefreshDatabase;
    use UserForTenant;

    protected $tenancy = true;
    protected bool $tenancy_make_databases = false;

    public function testIndex()
    {
        tenant()->domains()->delete();
        tenant()->domains()->create([
            'domain' => 'foo.com'
        ]);
        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->getJson('/api/settings/domains');

        $response->assertStatus(200);
        $this->assertArrayHasKey('data', $response->json());
        $this->assertCount(1, $response->json('data'));
        $this->assertArrayHasKey('domain', $response->json('data.0'));
        $this->assertArrayHasKey('primary', $response->json('data.0'));
        $this->assertArrayHasKey('temporary', $response->json('data.0'));
    }

    public function testStore()
    {
        tenant()->domains()->delete();
        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->postJson('/api/settings/domains', [
                'domain' => 'foo.com'
            ]);

        $response->assertStatus(200);
        $this->assertArrayHasKey('data', $response->json());
        $this->assertCount(1, $response->json('data'));
        $this->assertArrayHasKey('domain', $response->json('data.0'));
        $this->assertEquals('foo.com', $response->json('data.0.domain'));
        $this->assertArrayHasKey('primary', $response->json('data.0'));
        $this->assertArrayHasKey('temporary', $response->json('data.0'));
    }

    public function testDestroy()
    {
        $domain = tenant()->domains()->create([
            'domain' => 'foo.com'
        ]);
        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->deleteJson('/api/settings/domains/' . $domain->id);

        $response->assertStatus(200);
        $this->assertFalse(tenant()->domains()->where('domain', 'foo.com')->exists());
    }

    public function testMakePrimary()
    {
        $domain = tenant()->domains()->create([
            'domain' => 'foo.com'
        ]);

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->putJson('/api/settings/domains/' . $domain->id . '/make-primary');

        $response->assertStatus(200);
        $this->assertTrue(tenant()->domains()->where('primary', 1)->exists());
    }
}
