<?php
declare(strict_types=1);

namespace Autogedal\EanTools\Model\Spreadsheet;

use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem\Io\File;

class Format
{
    public const CSV = 'csv';
    public const XLSX = 'xlsx';

    public const DEFAULT_FORMAT = self::CSV;

    private const CSV_EXTENSIONS = ['csv', 'txt'];

    private const LABELS = [
        self::CSV => 'CSV',
        self::XLSX => 'XLSX',
    ];

    private const MIME_TYPES = [
        self::CSV => 'text/csv',
        self::XLSX => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    ];

    public function __construct(private readonly File $file)
    {
    }

    public function isSupported(string $format): bool
    {
        return isset(self::LABELS[$format]);
    }

    public function resolve(mixed $format): string
    {
        return is_string($format) && $this->isSupported($format)
            ? $format
            : self::DEFAULT_FORMAT;
    }

    public function fromFileName(string $fileName): string
    {
        $pathInfo = $this->file->getPathInfo($fileName);
        $extension = strtolower((string)($pathInfo['extension'] ?? ''));

        if (in_array($extension, self::CSV_EXTENSIONS, true)) {
            return self::CSV;
        }

        if ($extension === self::XLSX) {
            return self::XLSX;
        }

        throw new LocalizedException(
            __('The "%1" file has an unrecognized extension. CSV, TXT, and XLSX are supported.', $fileName)
        );
    }

    public function getExtension(string $format): string
    {
        return $this->resolve($format);
    }

    public function getMimeType(string $format): string
    {
        return self::MIME_TYPES[$this->resolve($format)];
    }

    public function getOptions(): array
    {
        return self::LABELS;
    }
}
