<?php

namespace Tests\Feature;

use App\Models\ArchiveSetting;
use App\Models\ClientCase;
use App\Models\Contract;
use App\Models\Segment;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;

class ArchiveContractSegmentTest extends \Tests\TestCase
{
    use RefreshDatabase;

    public function test_moves_contract_to_archive_segment_when_setting_has_segment_id(): void
    {
        $case = ClientCase::factory()->create();
        $contract = Contract::factory()->create([
            'client_case_id' => $case->id,
            'active' => 1,
        ]);

        $originalSegment = Segment::factory()->create(['active' => true]);
        $archiveSegment = Segment::factory()->create(['active' => true]);

        DB::table('client_case_segment')->insert([
            'client_case_id' => $case->id,
            'segment_id' => $originalSegment->id,
            'active' => true,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
        DB::table('contract_segment')->insert([
            'contract_id' => $contract->id,
            'segment_id' => $originalSegment->id,
            'active' => true,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        ArchiveSetting::factory()->create([
            'enabled' => true,
            'strategy' => 'manual',
            'segment_id' => $archiveSegment->id,
            'entities' => [
                ['table' => 'contracts', 'focus' => true],
            ],
        ]);

        $user = User::factory()->create();
        $this->actingAs($user);

        $response = $this->post(route('clientCase.contract.archive', ['client_case' => $case->uuid, 'uuid' => $contract->uuid]));
        $response->assertRedirect();

        $activePivots = DB::table('contract_segment')
            ->where('contract_id', $contract->id)
            ->where('active', true)
            ->pluck('segment_id');

        $this->assertTrue($activePivots->contains($archiveSegment->id));
        $this->assertFalse($activePivots->contains($originalSegment->id));
    }
}
