<?php

namespace Tests\Feature;

use App\DashboardRepository;
use Illuminate\Support\Facades\App;
use Mockery\MockInterface;
use Tests\DatabaseTestCase;
use Tests\UserForTenant;

class WidgetTest extends DatabaseTestCase
{
    use UserForTenant;

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

        $this->partialMock(DashboardRepository::class, function (MockInterface $mock) {
            $mock->shouldReceive('mapData')
                ->andReturnUsing(function ($widget) {
                    $widget['data'] = [];
                    return $widget;
                });
        });
    }

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

        $response->assertStatus(200);
        $this->assertIsArray($response->json());
        $this->assertArrayHasKey('kind', $response->json('0'));
        $this->assertArrayHasKey('widget', $response->json('0'));
        $this->assertArrayHasKey('data', $response->json('0'));
    }

    public function testGetAvailableWidgets()
    {
        $response = $this->actingAs($this->getUser(false))
            ->withHeader('X-Tenant', tenant('id'))
            ->getJson(route('tenant.user.get-dashboard-widgets', 'home'));

        $response->assertStatus(200);
        $this->assertIsArray($response->json());
        $this->assertArrayHasKey('kind', $response->json('0'));
        $this->assertArrayHasKey('widget', $response->json('0'));
        $this->assertArrayHasKey('data', $response->json('0'));
    }

    public function testSetAndLoadUserSpecificWidgets()
    {
        $response = $this->actingAs($this->getUser(false))
            ->withHeader('X-Tenant', tenant('id'))
            ->putJson(route('tenant.user.set-dashboard-widgets', 'home'), [
                'widgets' => [
                    [
                        'widget' => 'enquiries',
                        'data' => [],
                    ],
                    [
                        'widget' => 'recent-vehicles',
                        'data' => [],
                    ],
                ]
            ]);

        $response->assertStatus(200);

        $response = $this->actingAs($this->getUser(false))
            ->withHeader('X-Tenant', tenant('id'))
            ->getJson('/api/dashboard');

        $response->assertStatus(200);
        $this->assertIsArray($response->json());
        $this->assertCount(2, $response->json());
        $this->assertEquals('enquiries', $response->json('0.widget'));
        $this->assertEquals('recent-vehicles', $response->json('1.widget'));

    }

    public function testLoadCustomSectionWidgets()
    {
        $repository = App::make(DashboardRepository::class);
        $response = $repository->load($this->getUser(false), 'custom');
        $this->assertIsArray($response);
        $this->assertCount(0, $response);
    }
}
