<?php

namespace Tests\Unit;

use App\Campaigns\PerformanceDailyHistory;
use App\Campaigns\PerformanceDay;
use Illuminate\Support\Carbon;
use Tests\TestCase;

class PerformanceDailyHistoryTest extends TestCase
{
    public function test_it_keeps_in_window_days_and_joins_results_onto_the_same_date(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $history = PerformanceDailyHistory::fromDays(collect([
            new PerformanceDay(
                stat_date: Carbon::parse('2026-08-01'),
                spend: 99,
                impressions: 10,
                clicks: 1,
            ),
            new PerformanceDay(
                stat_date: Carbon::parse('2026-09-20'),
                spend: 20,
                impressions: 800,
                clicks: 4,
                conversions: 1,
                conversion_value: 5,
            ),
        ]), [
            ['date' => '2026-09-20', 'orders' => 2, 'revenue' => 50],
            ['date' => '2026-09-21', 'orders' => 1, 'revenue' => 8],
            ['date' => '2026-08-01', 'orders' => 9, 'revenue' => 90],
        ]);

        $this->assertSame('2026-08-24', $history['from']);
        $this->assertSame('2026-09-22', $history['to']);
        $this->assertSame(30, $history['expected_days']);
        $this->assertSame(2, $history['days_on_file']);
        $this->assertSame(['2026-09-20', '2026-09-21'], array_column($history['rows'], 'date'));
        $this->assertTrue($history['rows'][0]['platform_row']);
        $this->assertEquals(20, $history['rows'][0]['spend']);
        $this->assertEquals(4, $history['rows'][0]['clicks']);
        $this->assertEquals(0.005, $history['rows'][0]['ctr']);
        $this->assertEquals(2, $history['rows'][0]['orders']);
        $this->assertEquals(50, $history['rows'][0]['revenue']);
        $this->assertFalse($history['rows'][1]['platform_row']);
        $this->assertNull($history['rows'][1]['spend']);
        $this->assertEquals(1, $history['rows'][1]['orders']);
    }
}
