<?php

namespace Tests\Feature;

use App\DashboardRepository;
use App\Facades\Feature;
use Mockery\MockInterface;
use Tests\DatabaseTestCase;
use Tests\UserForTenant;

class DashboardFeatureGatingTest extends DatabaseTestCase
{
    use UserForTenant;

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

        // Avoid loading real widget data; we only assert which widgets are present.
        $this->partialMock(DashboardRepository::class, function (MockInterface $mock) {
            $mock->shouldReceive('mapData')
                ->andReturnUsing(function ($widget) {
                    $widget['data'] = [];
                    return $widget;
                });
        });
    }

    public function testReservationTilesHiddenWhenFeatureDisabled(): void
    {
        $widgets = $this->loadHomeDashboard();

        $this->assertNotContains('reservations_today', $widgets);
        $this->assertNotContains('reservations_revenue_today', $widgets);
    }

    public function testReservationTilesShownWhenFeatureEnabled(): void
    {
        Feature::setEnabled(tenant(), ['reservations']);

        $widgets = $this->loadHomeDashboard();

        $this->assertContains('reservations_today', $widgets);
        $this->assertContains('reservations_revenue_today', $widgets);
    }

    public function testServiceBookingTileGatedByFeature(): void
    {
        $this->assertNotContains('service_bookings_today', $this->loadHomeDashboard());

        Feature::setEnabled(tenant(), ['service-booking']);

        $this->assertContains('service_bookings_today', $this->loadHomeDashboard());
    }

    public function testPopularOffersAndNewCarsGatedByNewVehiclesFeature(): void
    {
        $widgets = $this->loadHomeDashboard();
        $this->assertNotContains('popular-offers', $widgets);
        $this->assertNotContains('popular-new-cars', $widgets);
        $this->assertNotContains('recent-offers', $widgets);

        Feature::setEnabled(tenant(), ['new-vehicles']);

        $widgets = $this->loadHomeDashboard();
        $this->assertContains('popular-offers', $widgets);
        $this->assertContains('popular-new-cars', $widgets);
        $this->assertContains('recent-offers', $widgets);
    }

    private function loadHomeDashboard(): array
    {
        $response = $this->actingAs($this->getUser(false))
            ->withHeader('X-Tenant', tenant('id'))
            ->getJson('/api/dashboard');

        $response->assertStatus(200);

        return collect($response->json())->pluck('widget')->all();
    }
}
