<?php

namespace Ignite\Core\Tests\Unit\Files;

use Ignite\Core\Files\TemporaryFile;
use Ignite\Core\Files\TemporaryFileBuilder;
use Ignite\Core\Tests\TestCase;
use Illuminate\Support\Facades\Storage;

class TemporaryFileBuilderTest extends TestCase
{
    /** @test */
    public function builds_temporary_files()
    {
        // Arrange
        Storage::fake();

        // Execute
        $tempFile = TemporaryFileBuilder::start()->make('temp file contents');

        // Check
        $this->assertInstanceOf(TemporaryFile::class, $tempFile);
        $this->assertEquals('temp file contents', $tempFile->get());
        $tempFile->assertExists();
        $this->assertEquals('', pathinfo($tempFile->getRelativePath(), PATHINFO_EXTENSION));
        $this->assertEquals('/', dirname($tempFile->getRelativePath()));
        $this->assertEquals(config('filesystems.default'), $tempFile->getDisk());
    }

    /** @test */
    public function builds_theoretical_temporary_files()
    {
        // Execute
        $tempFile = TemporaryFileBuilder::start()->make();

        // Check
        $this->assertInstanceOf(TemporaryFile::class, $tempFile);
        $this->assertFalse($tempFile->exists());
        $tempFile->assertMissing();
    }

    /** @test */
    public function can_provide_a_custom_prefix_and_extension_for_the_files()
    {
        // Execute
        $tempFile = TemporaryFileBuilder::start()
            ->prefix('my-prefix')
            ->extension('pdf')
            ->make();

        // Check
        $this->assertStringStartsWith('/my-prefix', $tempFile->getRelativePath());
        $this->assertEquals('pdf', pathinfo($tempFile->getRelativePath(), PATHINFO_EXTENSION));
    }

    /** @test */
    public function can_save_to_a_specific_disk_and_directory()
    {
        // Arrange
        Storage::fake('some-disk');

        // Execute
        $tempFile = TemporaryFileBuilder::start()
            ->disk('some-disk')
            ->directory('dir1/sub-dir1')
            ->make();

        // Check
        $this->assertEquals('dir1/sub-dir1', dirname($tempFile->getRelativePath()));
        $this->assertEquals('some-disk', $tempFile->getDisk());
    }

    /** @test */
    public function can_set_prefix_based_on_an_object()
    {
        // Execute
        $tempFile = TemporaryFileBuilder::start()
            ->prefix($this)
            ->make();

        // Check
        $this->assertStringStartsWith('/temporary_file_builder_test', $tempFile->getRelativePath());
    }
}
