<?php

namespace Tests\Tenant\Services;

use App\Services\GraphService;
use Illuminate\Support\Facades\Http;
use Tests\TenantTestCase;

class GraphServiceTest extends TenantTestCase
{
    public function testReturnsGraphResponseShape(): void
    {
        Http::fake();

        $response = app(GraphService::class)->getGraph([
            'metrics' => 'vehicles',
            'date_range' => 7,
        ]);

        $this->assertSame('ok', $response['status']);
        $this->assertSame('vehicles', $response['type']);
        $this->assertSame(7, $response['date_range']);
        $this->assertArrayHasKey('labels', $response);
        $this->assertArrayHasKey('datasets', $response);
    }

    public function testUnknownMetricReturnsEmptyDatasets(): void
    {
        Http::fake();

        $response = app(GraphService::class)->getGraph([
            'metrics' => 'no-such-metric',
            'date_range' => 7,
        ]);

        $this->assertSame('ok', $response['status']);
        $this->assertSame([], $response['datasets']);
    }

    public function testCustomFromToRangeIsHonoured(): void
    {
        Http::fake();

        $response = app(GraphService::class)->getGraph([
            'metrics' => 'vehicles',
            'from_date' => '2024-01-01',
            'to_date' => '2024-01-05',
        ]);

        $this->assertSame('ok', $response['status']);
        $this->assertSame('2024-01-01', $response['from']);
        $this->assertSame('2024-01-05', $response['to']);
        $this->assertSame(4, $response['date_range']);
        // Inclusive day range: 1st through 5th == 5 labels.
        $this->assertCount(5, $response['labels']);
    }

    public function testDateRangeFallbackUsedWhenNoCustomRange(): void
    {
        Http::fake();

        $response = app(GraphService::class)->getGraph([
            'metrics' => 'vehicles',
            'date_range' => 14,
        ]);

        $this->assertSame('ok', $response['status']);
        $this->assertSame(14, $response['date_range']);
    }

    public function testSingleMetricGraphsReturnOneDataset(): void
    {
        Http::fake();

        foreach (['enquiries', 'vehicles', 'vehicles-added', 'vehicles-removed', 'vehicles-reserved'] as $metric) {
            $response = app(GraphService::class)->getGraph([
                'metrics' => $metric,
                'date_range' => 7,
            ]);

            $this->assertSame('ok', $response['status'], $metric);
            $this->assertSame($metric, $response['type']);
            $this->assertCount(1, $response['datasets'], "$metric should have a single series");
        }
    }
}
