<?php

namespace Ignite\Core\Tests\Feature\Http\Controllers\Admin;

use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Ignite\Core\Entities\Import;
use Ignite\Core\Tests\TestCase;
use Ignite\Core\Services\Importers\Transactions;

class ImportControllerTest extends TestCase
{
    use RefreshDatabase;

    /**
     * Set up the test.
     *
     * @return void
     */
    public function setUp() : void
    {
        parent::setUp();

        $this->loadRoutes(['Core']);
    }

    /**
     * @test
     * @group Import
     * @group Feature
     */
    public function it_will_create_the_bare_necessities_for_an_import_and_redirect_to_the_resource_page()
    {
        $this->withoutMiddleware();
        $this->loginAsAdmin();

        $service = Transactions::class;

        $this->app['config']->set('core.import.types.transaction', [
            'label' => 'Transaction',
            'class' => $service
        ]);

        $knownDate = Carbon::create(2018, 3, 13, 12);
        Carbon::setTestNow($knownDate);

        Storage::fake('local');

        $response = $this->post(route('admin.import.store'), [
            'type' => $service,
            'file' => UploadedFile::fake()->create('fake-import.csv', 100)
        ]);

        $this->assertDatabaseHas('core_import', [
            'type' => $service,
            'file' => 'imports/transaction-' . $knownDate->format('YmdHis') . '.csv'
        ]);

        $response->assertRedirect(route('admin.import.show', Import::query()->first()));
    }

    /**
     * @test
     * @group Import
     * @group Feature
     */
    public function it_will_redirect_with_errors_when_the_type_is_missing()
    {
        $this->withoutMiddleware();
        $user = factory(\Ignite\Core\Entities\User::class)->create();
        $user = $this->loginAsAdmin($user->getKey());
        $service = Transactions::class;
        $this->app['config']->set('core.import.types.transaction', [
            'label' => 'Transaction',
            'class' => $service
        ]);

        $this->post(route('admin.import.store'), [
            'type' => '',
            'file' => UploadedFile::fake()->create('fake-import.csv', 100)
        ])->assertSessionHasErrors('type');
    }

    /**
     * @test
     * @group Import
     * @group Feature
     */
    public function it_will_redirect_with_errors_when_the_file_is_missing()
    {
        $this->withoutMiddleware();
        $user = factory(\Ignite\Core\Entities\User::class)->create();
        $user = $this->loginAsAdmin($user->getKey());
        $service = Transactions::class;
        $this->app['config']->set('core.import.types.transaction', [
            'label' => 'Transaction',
            'class' => $service
        ]);

        $this->post(route('admin.import.store'), [
            'type' => $service,
            'file' => ''
        ])->assertSessionHasErrors('file');
    }
}
