<?php

namespace Tests\Tenant\Controllers;

use Carbon\Carbon;
use Mtc\Crm\Models\EnquiryType;
use Mtc\MercuryDataModels\Enquiry;
use Tests\TenantTestCase;
use Tests\UserForTenant;

class DashboardEnquiriesByTypeTest extends TenantTestCase
{
    use UserForTenant;

    public function testReturnsEnquiryCountsGroupedByTypeOrderedDesc(): void
    {
        $sales = EnquiryType::factory()->create(['name' => 'Sales']);
        $service = EnquiryType::factory()->create(['name' => 'Service']);

        Enquiry::factory()->count(3)->create(['type_id' => $sales->id, 'ingested_at' => Carbon::now()]);
        Enquiry::factory()->create(['type_id' => $service->id, 'ingested_at' => Carbon::now()]);

        $response = $this->postBreakdown(Carbon::now()->subDays(7), Carbon::now());

        $response->assertStatus(200);
        $this->assertSame('ok', $response->json('status'));
        $this->assertEqualsCanonicalizing(['Sales', 'Service'], $response->json('labels'));
        $this->assertNotContains('Total', $response->json('labels'));

        // Ordered by count descending: Sales (3) before Service (1).
        $this->assertSame('Sales', $response->json('labels.0'));
        $this->assertEquals(3, $response->json('data.0'));
    }

    public function testExcludesEnquiriesOutsideTheRange(): void
    {
        $type = EnquiryType::factory()->create(['name' => 'Sales']);
        Enquiry::factory()->create(['type_id' => $type->id, 'ingested_at' => Carbon::now()->subDays(60)]);

        $response = $this->postBreakdown(Carbon::now()->subDays(7), Carbon::now());

        $response->assertStatus(200);
        $this->assertEmpty($response->json('labels'));
        $this->assertEmpty($response->json('data'));
    }

    private function postBreakdown(Carbon $from, Carbon $to)
    {
        return $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->postJson(route('tenant.dashboard.enquiries-by-type'), [
                'from_date' => $from->format('Y-m-d'),
                'to_date' => $to->format('Y-m-d'),
            ]);
    }
}
