<?php

namespace Tests\Feature;

use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\Tenant;
use Tests\DatabaseTestCase;

/**
 * These tests run in real-tenant mode (DatabaseTestCase defaults to a master DB).
 * The setup creates a single tenant whose domain is "demo.com" (see
 * UsesTenancy::initializeRealTenant), and asTenant() sends that same value in the
 * x-tenant header. So throughout, demo.com is the current tenant's own domain.
 */
class CorsAllowedOriginsTest extends DatabaseTestCase
{
    public function testPreflightFromRegisteredDomainIsReflectedWithCredentials()
    {
        // No x-tenant on a preflight, so it is validated against the global domains table.
        $this->options(route('dealerships.index'), [], [
            'Origin' => 'https://demo.com',
            'Access-Control-Request-Method' => 'GET',
        ])
            ->assertNoContent()
            ->assertHeader('Access-Control-Allow-Origin', 'https://demo.com')
            ->assertHeader('Access-Control-Allow-Credentials', 'true');
    }

    public function testPreflightFromUnknownOriginIsNotReflected()
    {
        $this->options(route('dealerships.index'), [], [
            'Origin' => 'https://evil.example',
            'Access-Control-Request-Method' => 'GET',
        ])->assertHeaderMissing('Access-Control-Allow-Origin');
    }

    public function testActualRequestFromSameTenantOriginIsReflected()
    {
        Dealership::factory()->create();

        $this->asTenant(tenant())
            ->withHeader('Origin', 'https://demo.com')
            ->getJson(route('dealerships.index'))
            ->assertOk()
            ->assertHeader('Access-Control-Allow-Origin', 'https://demo.com')
            ->assertHeader('Access-Control-Allow-Credentials', 'true');
    }

    public function testActualRequestFromAnotherTenantsDomainIsBlocked()
    {
        Dealership::factory()->create();

        // A registered domain, but belonging to a different tenant than x-tenant (demo.com).
        $other = Tenant::create(['tier' => 'pro']);
        $other->domains()->create(['domain' => 'other-tenant.com']);

        $this->asTenant(tenant())
            ->withHeader('Origin', 'https://other-tenant.com')
            ->getJson(route('dealerships.index'))
            ->assertOk()
            ->assertHeaderMissing('Access-Control-Allow-Origin');
    }
}
