<?php

namespace Tests\Tenant\Reporting;

use App\Reporting\Repositories\CRMReportRepository;
use Carbon\Carbon;
use Illuminate\Support\Facades\App;
use Mtc\MercuryDataModels\Enquiry;
use Tests\TenantTestCase;

class EnquiryTimingBreakdownTest extends TenantTestCase
{
    public function testWeekdayBreakdownReturnsMondayFirstZeroFilledCounts(): void
    {
        // Last week's Monday, so the whole Mon–Sun week is in the past and inside the range
        // regardless of which day the test runs on.
        $monday = Carbon::now()->startOfDay()->subDays(Carbon::now()->dayOfWeekIso - 1 + 7);
        $wednesday = $monday->copy()->addDays(2);

        Enquiry::factory()->create(['ingested_at' => $monday->copy()->setTime(9, 15)]);
        Enquiry::factory()->create(['ingested_at' => $monday->copy()->setTime(9, 45)]);
        Enquiry::factory()->create(['ingested_at' => $wednesday->copy()->setTime(14, 0)]);

        $results = App::make(CRMReportRepository::class)->weekdayBreakdown(
            Carbon::now()->subDays(90)->startOfDay(),
            Carbon::now()->endOfDay(),
        );

        $this->assertCount(7, $results);
        $this->assertSame('Monday', $results->first()['label']);
        $this->assertSame('Sunday', $results->last()['label']);

        $byLabel = $results->keyBy('label');
        $this->assertSame(2, $byLabel['Monday']['enquiry_count']);
        $this->assertSame(1, $byLabel['Wednesday']['enquiry_count']);
        $this->assertSame(0, $byLabel['Tuesday']['enquiry_count']);
        $this->assertSame(0, $byLabel['Sunday']['enquiry_count']);
    }

    public function testTimeOfDayBreakdownReturnsAll24HoursZeroFilled(): void
    {
        $day = Carbon::now()->startOfDay()->subDays(Carbon::now()->dayOfWeekIso - 1 + 7);

        Enquiry::factory()->create(['ingested_at' => $day->copy()->setTime(9, 15)]);
        Enquiry::factory()->create(['ingested_at' => $day->copy()->setTime(9, 55)]);
        Enquiry::factory()->create(['ingested_at' => $day->copy()->setTime(14, 0)]);

        $results = App::make(CRMReportRepository::class)->timeOfDayBreakdown(
            Carbon::now()->subDays(90)->startOfDay(),
            Carbon::now()->endOfDay(),
        );

        $this->assertCount(24, $results);
        $this->assertSame('00:00', $results->first()['label']);
        $this->assertSame('23:00', $results->last()['label']);

        // The collection is 0-indexed by hour, so index === hour of day.
        $this->assertSame(2, $results[9]['enquiry_count']);
        $this->assertSame(1, $results[14]['enquiry_count']);
        $this->assertSame(0, $results[0]['enquiry_count']);
    }
}
