<?php

namespace Ignite\Core\Tests\Unit\Files\Processors;

use Ignite\Core\Database\Seeders\UserTableSeeder;
use Ignite\Core\Files\File;
use Ignite\Core\Files\Processors\ToImport;
use Ignite\Core\Services\Importers\Participants;
use Ignite\Core\Tests\TestCase;
use Illuminate\Foundation\Console\QueuedCommand;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;

class ToImportTest extends TestCase
{
    use DatabaseMigrations;

    protected function setUp(): void
    {
        parent::setUp();
        Storage::fake();
        Queue::fake();
        $this->seed(UserTableSeeder::class);
    }

    /** @test */
    public function converts_the_file_to_an_import()
    {
        // Arrange
        $file = new File('SomeFile.txt');
        $file->put('some contents!!');

        // Pre-check
        $this->assertDatabaseCount('core_import', 0);

        // Execute
        $processedFile = ToImport::forType(Participants::class)->run($file);

        // Check
        $file->assertMissing();
        $this->assertMatchesRegularExpression('#'.config('config.import.directory').'/.*\d+\.csv#', $processedFile->getRelativePath());
        $this->assertEquals('some contents!!', $processedFile->get());
        $this->assertDatabaseCount('core_import', 1);
        Queue::assertNothingPushed(); // Did not kick off the import.
    }

    /** @test */
    public function keeps_the_original_file_if_asked()
    {
        // Arrange
        $file = new File('OriginalFile.txt');
        $file->put('some contents!!');

        // Execute
        ToImport::forType(Participants::class)
            ->keepOriginal()
            ->run($file);

        // Check
        $file->assertExists();
    }

    /** @test */
    public function kicks_off_the_import_if_asked()
    {
        // Arrange
        $file = new File('OriginalFile.txt');
        $file->put('some contents!!');

        // Execute
        ToImport::forType(Participants::class)
            ->andQueue()
            ->run($file);

        // Check
        Queue::assertPushedOn(config('core.import.queue_connection'), QueuedCommand::class);
    }
}
