<?php

namespace Ignite\Core\Tests\Unit\Services;

use Ignite\Core\Models\Report\EnrollmentReport;
use Ignite\Core\Services\Reports\ReportDownloadRequest;
use Ignite\Core\Tests\TestCase;
use Illuminate\Http\Request;
use InvalidArgumentException;

class ReportDownloadRequestTest extends TestCase
{
    /**
     * @test
     */
    public function itCapturesOnlyTheTableStateNeededByTheQueue(): void
    {
        $httpRequest = Request::create('/', 'POST', [
            'filters' => ['status' => ['active']],
            'columns' => [
                ['data' => 'first', 'search' => ['value' => 'Ada']],
                ['data' => 'last', 'search' => ['value' => '']],
            ],
            'order' => [['column' => 1, 'dir' => 'DESC']],
            'search' => ['value' => 'Lovelace'],
            'visible_columns' => ['first', 'last'],
            // This unrelated request state must never be persisted in a queue payload.
            '_token' => 'secret-csrf-value',
            'length' => 25,
        ]);

        $data = ReportDownloadRequest::fromHttpRequest(
            $httpRequest,
            42,
            EnrollmentReport::class,
            'Enrollment Report',
            ReportDownloadRequest::FORMAT_XLSX,
            ['report_id' => 7]
        )->toArray();

        $this->assertSame(['status' => ['active']], $data['filters']);
        $this->assertSame([['column' => 'last', 'direction' => 'desc']], $data['sort']);
        $this->assertSame(
            ['value' => 'Lovelace', 'columns' => ['first' => 'Ada']],
            $data['search']
        );
        $this->assertSame(['first', 'last'], $data['visible_columns']);
        $this->assertSame(['report_id' => 7], $data['source']['params']);
        $this->assertArrayNotHasKey('_token', $data);
        $this->assertArrayNotHasKey('length', $data);
    }

    /**
     * @test
     */
    public function itRejectsInvalidOrUnsafeRequestDescriptions(): void
    {
        $this->expectException(InvalidArgumentException::class);

        ReportDownloadRequest::forTable(
            0,
            EnrollmentReport::class,
            'Invalid Request'
        );
    }
}
