<?php

namespace Tests\Unit\Services;

use App\Enums\ActivityTypeEnum;
use App\Models\ActivityLog;
use App\Services\Activity\ActivitySummary;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ActivitySummaryTest extends TestCase
{
    use RefreshDatabase;

    public function test_counts_are_grouped_per_type(): void
    {
        ActivityLog::factory()->count(3)->type(ActivityTypeEnum::FETCH)->create();
        ActivityLog::factory()->count(2)->type(ActivityTypeEnum::PUBLISH)->create();

        $summary = (new ActivitySummary)->since(now()->subDay());

        $this->assertSame(3, $summary[ActivityTypeEnum::FETCH->value]);
        $this->assertSame(2, $summary[ActivityTypeEnum::PUBLISH->value]);
    }

    public function test_every_type_is_present_even_with_no_rows(): void
    {
        $summary = (new ActivitySummary)->since(now()->subDay());

        foreach (ActivityTypeEnum::cases() as $case) {
            $this->assertArrayHasKey($case->value, $summary);
            $this->assertSame(0, $summary[$case->value]);
        }
    }

    public function test_entries_outside_the_window_are_not_counted(): void
    {
        ActivityLog::factory()->type(ActivityTypeEnum::FETCH)->loggedAt(now()->subHours(2))->create();
        ActivityLog::factory()->type(ActivityTypeEnum::FETCH)->loggedAt(now()->subDays(5))->create();

        $summary = (new ActivitySummary)->since(now()->subDay());

        $this->assertSame(1, $summary[ActivityTypeEnum::FETCH->value]);
    }

    public function test_uses_a_single_query(): void
    {
        ActivityLog::factory()->count(5)->create();

        \DB::enableQueryLog();
        (new ActivitySummary)->since(now()->subDay());
        $queries = \DB::getQueryLog();
        \DB::disableQueryLog();

        $this->assertCount(1, $queries);
    }
}
