<?php

namespace Tests\Feature;

use App\Domain\Clinical\TimelineService;
use App\Domain\Clinical\ToothChartService;
use App\Models\Patient;
use App\Models\Tenant;
use App\Models\TreatmentPlan;
use App\Support\Tenancy;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class TimelineTest extends TestCase
{
    use RefreshDatabase;

    public function test_timeline_merges_sources_newest_first(): void
    {
        $this->seed();
        $tenant = Tenant::create(['name' => 'Smile', 'slug' => 'smile']);
        app(Tenancy::class)->set($tenant);

        $patient = Patient::factory()->create();

        app(ToothChartService::class)->record($patient, 16, 'caries');
        sleep(0); // same-second ordering is fine; recorded_at vs created_at both now
        TreatmentPlan::factory()->create(['patient_id' => $patient->id]);

        $events = app(TimelineService::class)->for($patient);

        $this->assertGreaterThanOrEqual(2, $events->count());
        $types = $events->pluck('type');
        $this->assertTrue($types->contains('chart'));
        $this->assertTrue($types->contains('plan'));

        // sorted desc
        $times = $events->pluck('at')->map(fn ($t) => strtotime($t));
        $this->assertEquals($times->sortDesc()->values()->all(), $times->values()->all());
    }
}
