<?php

namespace Tests\Tenant\Controllers;

use Database\Seeders\Tenant\FixSiteAccessPasswordValidationSeed;
use Database\Seeders\Tenant\SiteAccessPasswordSeed;
use Database\Seeders\Tenant\SiteAccessRequestSeed;
use Illuminate\Support\Facades\Event;
use Tests\TenantTestCase;
use Tests\UserForTenant;

class SiteAccessSettingsValidationTest extends TenantTestCase
{
    use UserForTenant;

    protected bool $useTestSettingRepository = false;

    protected function setUp(): void
    {
        parent::setUp();
        Event::fake();
        (new SiteAccessPasswordSeed())->run();
        (new SiteAccessRequestSeed())->run();
        (new FixSiteAccessPasswordValidationSeed())->run();
    }

    public function testPasswordIsOptionalInEmailRequestMode(): void
    {
        $response = $this->updateSettings([
            ['config_key' => 'site-access-enabled', 'value' => true],
            ['config_key' => 'site-access-mode', 'value' => 'email-request'],
            ['config_key' => 'site-access-password', 'value' => ''],
            ['config_key' => 'site-access-whitelisted-domains', 'value' => 'mtc.co.uk'],
        ]);

        $response->assertStatus(200);
    }

    public function testPasswordIsRequiredInPasswordMode(): void
    {
        $response = $this->updateSettings([
            ['config_key' => 'site-access-enabled', 'value' => true],
            ['config_key' => 'site-access-mode', 'value' => 'password'],
            ['config_key' => 'site-access-password', 'value' => ''],
        ]);

        $response->assertStatus(422);
        $response->assertJsonValidationErrors('values.site-access-password');
    }

    /**
     * @param  list<array{config_key: string, value: mixed}>  $settings
     */
    private function updateSettings(array $settings): \Illuminate\Testing\TestResponse
    {
        return $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->putJson(route('tenant.settings.update', 'General'), ['settings' => $settings]);
    }
}
