<?php

namespace Tests\Feature;

use App\Models\Company;
use App\Models\Lead;
use App\Models\PipelineStage;
use App\Models\User;
use App\Services\CompanySetupService;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class TenantLeadIsolationTest extends TestCase
{
    use RefreshDatabase;

    public function test_lead_from_other_company_is_not_visible(): void
    {
        $this->seed(DatabaseSeeder::class);

        $companyA = Company::factory()->create();
        $companyB = Company::factory()->create();

        $setup = app(CompanySetupService::class);
        $setup->seedDefaultPipeline($companyA);
        $setup->seedDefaultPipeline($companyB);

        $userA = User::factory()->create(['company_id' => $companyA->id]);
        $userA->assignRole('admin');

        $stageB = PipelineStage::withoutGlobalScope('company')
            ->where('company_id', $companyB->id)
            ->firstOrFail();

        $leadB = Lead::withoutGlobalScope('company')->create([
            'company_id' => $companyB->id,
            'pipeline_stage_id' => $stageB->id,
            'name' => 'Secret lead',
        ]);

        $this->actingAs($userA);

        $this->get(route('leads.show', $leadB))->assertNotFound();
    }
}
