<?php

namespace Tests\Tenant\Controllers;

use Carbon\Carbon;
use Mtc\MercuryDataModels\ReportingStat;
use Tests\TenantTestCase;
use Tests\UserForTenant;

class EnquiryUtmEndpointsTest extends TenantTestCase
{
    use UserForTenant;

    protected function setUp(): void
    {
        parent::setUp();

        $this->stat('enquiry-utm:source:google', 5);
        $this->stat('enquiry-utm:source:facebook', 2);
        $this->stat('enquiry-utm:medium:cpc', 4);
    }

    public function testDashboardEndpointReturnsDoughnutDataForDimension(): void
    {
        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->postJson(route('tenant.dashboard.enquiries-by-utm'), [
                'dimension' => 'source',
                'from_date' => Carbon::now()->subDays(7)->format('Y-m-d'),
                'to_date' => Carbon::now()->format('Y-m-d'),
            ]);

        $response->assertStatus(200);
        $this->assertSame('ok', $response->json('status'));
        $this->assertSame('source', $response->json('dimension'));
        $this->assertSame(['google', 'facebook'], $response->json('labels'));
        $this->assertSame([5, 2], $response->json('data'));
    }

    public function testDashboardEndpointSwitchesDimensionAndDefaultsToSource(): void
    {
        $medium = $this->postUtm(['dimension' => 'medium']);
        $this->assertSame(['cpc'], $medium->json('labels'));

        $default = $this->postUtm(['dimension' => 'bogus']);
        $this->assertSame('source', $default->json('dimension'));
    }

    public function testReportEndpointReturnsResultsForDimension(): void
    {
        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->postJson(route('tenant.reports.crm.utm-breakdown'), [
                'dimension' => 'source',
                'from' => Carbon::now()->subDays(7)->format('Y-m-d'),
                'to' => Carbon::now()->format('Y-m-d'),
            ]);

        $response->assertStatus(200);
        $this->assertSame('source', $response->json('dimension'));
        $this->assertSame('google', $response->json('results.0.type'));
        $this->assertSame(5, $response->json('results.0.enquiry_count'));
    }

    private function postUtm(array $payload)
    {
        return $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->postJson(route('tenant.dashboard.enquiries-by-utm'), $payload);
    }

    private function stat(string $key, int $value): void
    {
        ReportingStat::create([
            'key' => $key,
            'date' => Carbon::now()->format('Y-m-d'),
            'value' => $value,
        ]);
    }
}
