<?php

declare(strict_types=1);

use App\Models\Project;
use App\Models\Tenant;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\Concerns\SharesSupplierPdo;

// Без изоляции тест само-загрязнялся (проект теста 1 оставался для теста 2 → count=2)
// и протекал committed-проектами в глобальный скан snapshot:backfill для других тестов.
// SharesSupplierPdo — снапшот-вставка идёт через pgsql_supplier, проект создан через pgsql.
uses(DatabaseTransactions::class);
uses(SharesSupplierPdo::class);

it('creates snapshot for given date from current live state', function () {
    Carbon::setTestNow('2026-05-27 14:00:00', 'Europe/Moscow');
    $tenant = Tenant::factory()->create(['frozen_by_balance_at' => null]);
    Project::factory()->for($tenant)->asCallSignal('79161234567')->create([
        'is_active' => true,
        'delivery_days_mask' => 127,
        'daily_limit_target' => 10,
    ]);

    $this->artisan('snapshot:backfill', ['--date' => '2026-05-27'])
        ->assertSuccessful();

    expect(DB::table('project_routing_snapshots')->where('snapshot_date', '2026-05-27')->count())->toBe(1);
    Carbon::setTestNow();
});

it('is idempotent — does not duplicate on re-run', function () {
    Carbon::setTestNow('2026-05-27 14:00:00', 'Europe/Moscow');
    $tenant = Tenant::factory()->create(['frozen_by_balance_at' => null]);
    Project::factory()->for($tenant)->asCallSignal('79161234567')->create([
        'is_active' => true,
        'delivery_days_mask' => 127,
        'daily_limit_target' => 10,
    ]);

    $this->artisan('snapshot:backfill', ['--date' => '2026-05-27'])->assertSuccessful();
    $this->artisan('snapshot:backfill', ['--date' => '2026-05-27'])->assertSuccessful();

    expect(DB::table('project_routing_snapshots')->count())->toBe(1);
    Carbon::setTestNow();
});
