<?php

namespace Tests\Feature;

use App\Models\Account;
use App\Models\ArchiveSetting;
use App\Models\Booking;
use App\Models\ClientCase;
use App\Models\Contract;
use App\Models\Payment;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ArchiveContractChainedEntitiesTest extends \Tests\TestCase
{
    use RefreshDatabase;

    public function test_archives_payments_and_bookings_via_account_chain(): void
    {
        $case = ClientCase::factory()->create();
        $contract = Contract::factory()->create([
            'client_case_id' => $case->id,
            'active' => 1,
        ]);
        // Create account tied to contract
        // Minimal account type requirement
        $accountTypeId = \DB::table('account_types')->insertGetId([
            'name' => 'Test Type',
            'description' => 'Temp',
            'created_at' => now(),
            'updated_at' => now(),
            'deleted_at' => null,
        ]);
        $account = Account::create([
            'contract_id' => $contract->id,
            'type_id' => $accountTypeId,
            'active' => 1,
            'initial_amount' => 0,
            'balance_amount' => 0,
        ]);

        // Seed payments & bookings for that account
        $payment = Payment::create([
            'account_id' => $account->id,
            'amount_cents' => 10000,
            'currency' => 'EUR',
            'reference' => 'P-TEST',
            'paid_at' => now(),
            'meta' => json_encode([]),
        ]);
        $booking = Booking::create([
            'account_id' => $account->id,
            'payment_id' => $payment->id,
            'amount_cents' => 10000,
            'type' => 'debit',
            'description' => 'Test Booking',
            'booked_at' => now(),
        ]);

        ArchiveSetting::factory()->create([
            'enabled' => true,
            'strategy' => 'manual',
            'soft' => true,
            'entities' => [
                ['table' => 'contracts', 'focus' => true],
                ['table' => 'account.payments'],
                ['table' => 'account.bookings'],
            ],
        ]);

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

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

        // Refresh models
        $payment->refresh();
        $booking->refresh();

        $this->assertDatabaseHas('payments', ['id' => $payment->id, 'active' => 0]);
        $this->assertDatabaseHas('bookings', ['id' => $booking->id, 'active' => 0]);
    }
}
