<?php

namespace Ignite\Core\Tests\Unit\Files;

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

class TemporaryFileTest extends TestCase
{
    /** @test */
    public function deletes_itself_when_the_object_is_destroyed()
    {
        // Arrange
        $localFilesystem = Storage::fake('local');
        $file = TemporaryFileBuilder::start()->disk('local')->make('content');
        $path = $file->getRelativePath();

        // Pre-check
        $this->assertInstanceOf(TemporaryFile::class, $file);
        $localFilesystem->assertExists($path);

        // Execute
        unset($file);

        // Check
        $localFilesystem->assertMissing($path);
    }

    /** @test */
    public function can_be_converted_to_a_non_temporary_file()
    {
        // Arrange
        Storage::fake('local');
        $temporaryFile = new TemporaryFile('temp-path.txt');
        $temporaryFile->put('testing!');

        // Execute
        $file = $temporaryFile->keep();
        unset($temporaryFile);

        // Check
        $this->assertInstanceOf(File::class, $file);
        $this->assertNotInstanceOf(TemporaryFile::class, $file);
        File::new('temp-path.txt')->assertExists();
        $this->assertEquals(
            'testing!',
            File::new('temp-path.txt')->get(),
            'Temporary file should not have been deleted when object was destroyed'
        );
    }
}
