<?php

use App\Models\InventoryLink;
use App\Models\ManagedEnvironment;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;

uses(RefreshDatabase::class);

it('enforces unique constraint on inventory_links', function () {
    $tenant = ManagedEnvironment::factory()->create();

    $data = [
        'managed_environment_id' => $tenant->getKey(),
        'source_type' => 'inventory_item',
        'source_id' => (string) Str::uuid(),
        'target_type' => 'foundation_object',
        'target_id' => (string) Str::uuid(),
        'relationship_type' => 'assigned_to',
        'metadata' => ['last_known_name' => 'X'],
    ];

    InventoryLink::query()->create($data);

    expect(function () use ($data) {
        InventoryLink::query()->create($data);
    })->toThrow(QueryException::class);
});

it('scopes edges by tenant at query level', function () {
    $tenantA = ManagedEnvironment::factory()->create();
    $tenantB = ManagedEnvironment::factory()->create();

    $sourceId = (string) Str::uuid();

    InventoryLink::factory()->create([
        'managed_environment_id' => $tenantA->getKey(),
        'source_id' => $sourceId,
    ]);

    InventoryLink::factory()->create([
        'managed_environment_id' => $tenantB->getKey(),
        'source_id' => $sourceId,
    ]);

    $edgesA = InventoryLink::query()->where('managed_environment_id', $tenantA->getKey())->get();
    $edgesB = InventoryLink::query()->where('managed_environment_id', $tenantB->getKey())->get();

    expect($edgesA->count())->toBe(1);
    expect($edgesB->count())->toBe(1);
});
