<?php

namespace Tests\Feature\Migrations;

use Illuminate\Database\QueryException;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;

class SeparateTenantDomainAndBasePathTest extends TestCase
{
    private string $originalConnection;

    protected function setUp(): void
    {
        parent::setUp();

        $this->originalConnection = DB::getDefaultConnection();
        config()->set('database.connections.tenant_path_test', [
            'driver' => 'sqlite',
            'database' => ':memory:',
            'prefix' => '',
            'foreign_key_constraints' => true,
        ]);
        DB::setDefaultConnection('tenant_path_test');

        Schema::create('tenants', function (Blueprint $table): void {
            $table->id();
            $table->string('dominio');
            $table->unique('dominio', 'tenants_dominio_unique');
        });
    }

    protected function tearDown(): void
    {
        DB::purge('tenant_path_test');
        DB::setDefaultConnection($this->originalConnection);

        parent::tearDown();
    }

    public function test_it_splits_existing_tenant_keys_and_enforces_composite_uniqueness(): void
    {
        DB::table('tenants')->insert([
            ['dominio' => 'onticket.com.ar'],
            ['dominio' => 'onticket.com.ar/desfile/'],
            ['dominio' => 'https://ONTICKET.COM.AR/sonder'],
        ]);

        $migration = require database_path(
            'migrations/2026_08_18_060000_separate_tenant_domain_and_base_path.php'
        );
        $migration->up();

        $this->assertDatabaseHas('tenants', [
            'dominio' => 'onticket.com.ar',
            'base_path' => '/',
        ]);
        $this->assertDatabaseHas('tenants', [
            'dominio' => 'onticket.com.ar',
            'base_path' => '/desfile',
        ]);
        $this->assertDatabaseHas('tenants', [
            'dominio' => 'onticket.com.ar',
            'base_path' => '/sonder',
        ]);

        $this->expectException(QueryException::class);

        DB::table('tenants')->insert([
            'dominio' => 'onticket.com.ar',
            'base_path' => '/desfile',
        ]);
    }

    public function test_it_recombines_tenant_locations_when_rolled_back(): void
    {
        DB::table('tenants')->insert(['dominio' => 'onticket.com.ar/desfile']);

        $migration = require database_path(
            'migrations/2026_08_18_060000_separate_tenant_domain_and_base_path.php'
        );
        $migration->up();
        $migration->down();

        $this->assertFalse(Schema::hasColumn('tenants', 'base_path'));
        $this->assertDatabaseHas('tenants', [
            'dominio' => 'onticket.com.ar/desfile',
        ]);
    }
}
