<?php

declare(strict_types=1);

use App\Models\ProviderConnection;
use App\Models\ManagedEnvironment;
use Illuminate\Support\Facades\DB;

it('Spec081 keeps the partial unique default index for provider connections', function (): void {
    $driver = DB::connection()->getDriverName();

    if ($driver === 'sqlite') {
        $indexes = collect(DB::select("PRAGMA index_list('provider_connections')"))
            ->map(static fn (object $row): array => (array) $row);

        expect($indexes->pluck('name')->all())->toContain('provider_connections_default_unique');

        return;
    }

    $exists = DB::table('pg_indexes')
        ->where('tablename', 'provider_connections')
        ->where('indexname', 'provider_connections_default_unique')
        ->exists();

    expect($exists)->toBeTrue();
});

it('Spec081 makeDefault preserves one default per tenant and provider', function (): void {
    $tenant = ManagedEnvironment::factory()->create();

    $first = ProviderConnection::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'provider' => 'microsoft',
        'is_default' => true,
    ]);

    $second = ProviderConnection::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'provider' => 'microsoft',
        'is_default' => false,
    ]);

    $second->makeDefault();

    $defaults = ProviderConnection::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('provider', 'microsoft')
        ->where('is_default', true)
        ->pluck('id')
        ->all();

    expect($defaults)->toHaveCount(1)
        ->and((int) $defaults[0])->toBe((int) $second->getKey());

    $first->refresh();
    expect((bool) $first->is_default)->toBeFalse();
});
