<?php

use PHPUnit\Framework\TestCase;
use boru\boruai\Tools\Util;

class UtilTest extends TestCase
{
    /** @var string[] */
    private array $tempFiles = [];

    protected function tearDown(): void
    {
        foreach ($this->tempFiles as $file) {
            if (file_exists($file)) {
                unlink($file);
            }
        }

        $this->tempFiles = [];
    }

    public function testMimeTypeFromPathUsesKnownOfficeMappings(): void
    {
        $this->assertSame(
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            Util::mimeTypeFromPath('/tmp/report.xlsx')
        );

        $this->assertSame(
            'application/vnd.ms-excel',
            Util::mimeTypeFromPath('/tmp/report.xls')
        );

        $this->assertSame(
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            Util::mimeTypeFromPath('/tmp/report.docx')
        );
    }

    public function testMimeTypeFromPathFallsBackToProvidedMimeType(): void
    {
        $this->assertSame(
            'application/x-custom',
            Util::mimeTypeFromPath('/tmp/report.unknown', 'application/x-custom')
        );
    }

    public function testMakeBase64urlUsesKnownMimeTypeMappings(): void
    {
        $path = $this->makeTempFile('xlsx', 'spreadsheet bytes');

        $base64url = Util::makeBase64url($path);

        $this->assertStringStartsWith(
            'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,',
            $base64url
        );

        $encoded = substr($base64url, strpos($base64url, ',') + 1);
        $this->assertSame('spreadsheet bytes', base64_decode($encoded));
    }

    private function makeTempFile(string $extension, string $contents): string
    {
        $path = sys_get_temp_dir() . '/boruai-' . uniqid('', true) . '.' . $extension;
        file_put_contents($path, $contents);
        $this->tempFiles[] = $path;

        return $path;
    }
}
