<?php

declare(strict_types=1);

use App\Http\Resources\ProjectResource;
use App\Models\Project;
use App\Models\SupplierProject;
use App\Models\Tenant;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;

uses(DatabaseTransactions::class);

function linkedProject(bool $active, ?string $pausedAt = null): Project
{
    $tenant = Tenant::factory()->create();
    $p = Project::factory()->for($tenant)->create(['is_active' => $active, 'paused_at' => $pausedAt]);
    $sp = SupplierProject::factory()->create();
    DB::table('project_supplier_links')->insert([
        'project_id' => $p->id,
        'supplier_project_id' => $sp->id,
        'platform' => $sp->platform,
        'subject_code' => null,
    ]);

    return $p->loadCount('supplierProjects');
}

it('active linked project → source_locked true + projected', function (): void {
    $res = (new ProjectResource(linkedProject(true)))->toArray(request());
    expect($res)->toHaveKeys(['source_locked', 'source_unlock_at', 'source_unlock_projected']);
    expect($res['source_locked'])->toBeTrue();
    expect($res['source_unlock_projected'])->toBeTrue();
    expect($res['source_unlock_at'])->not->toBeNull();
});

it('project with no supplier links → source_locked false', function (): void {
    $tenant = Tenant::factory()->create();
    $p = Project::factory()->for($tenant)->create(['is_active' => true])->loadCount('supplierProjects');
    $res = (new ProjectResource($p))->toArray(request());
    expect($res['source_locked'])->toBeFalse();
    expect($res['source_unlock_at'])->toBeNull();
    expect($res['source_unlock_projected'])->toBeFalse();
});

it('отдаёт source_change_message (единый текст правила) для залоченного проекта', function (): void {
    $res = (new ProjectResource(linkedProject(true)))->toArray(request());
    expect($res['source_change_message'])->toBeString()
        ->and($res['source_change_message'])->toContain('по старому источнику');
});

it('source_change_message = null когда источник не залочен', function (): void {
    $tenant = Tenant::factory()->create();
    $p = Project::factory()->for($tenant)->create(['is_active' => true])->loadCount('supplierProjects');
    $res = (new ProjectResource($p))->toArray(request());
    expect($res['source_change_message'])->toBeNull();
});

it('paused linked project in grace → source_locked true, твёрдая дата, projected=false', function (): void {
    // На паузе час назад → в grace-окне (до следующего 21:00 МСК + 24ч).
    $res = (new ProjectResource(linkedProject(false, now()->subHour()->toDateTimeString())))->toArray(request());
    expect($res['source_locked'])->toBeTrue();
    // Дата — твёрдая (не прогноз «если поставить паузу сейчас»).
    expect($res['source_unlock_projected'])->toBeFalse();
    expect($res['source_unlock_at'])->not->toBeNull();
});
