<?php
declare(strict_types=1);

namespace Autogedal\EanTools\Model;

use Autogedal\EanTools\Model\Spreadsheet\RowReaderResolver;
use Magento\Framework\Exception\LocalizedException;

class EanColumnParser
{
    private const EAN_HEADERS = [
        'ean' => true,
        'ean13' => true,
        'ean_13' => true,
        'gtin' => true,
        'barcode' => true,
        'cod_bare' => true,
        'cod bare' => true,
        'emkp_ean' => true,
    ];

    public function __construct(private readonly RowReaderResolver $readerResolver)
    {
    }

    public function parseEanColumn(string $path, ?string $originalName = null): array
    {
        $reader = $this->readerResolver->forFile($path, $originalName);

        $rows = [];
        $column = null;

        foreach ($reader->read($path) as $line => $cells) {
            if ($column === null) {
                if (!$this->hasContent($cells)) {
                    continue;
                }

                [$column, $isHeader] = $this->resolveColumn($cells);
                if ($isHeader) {
                    continue;
                }
            }

            $value = $cells[$column] ?? '';
            if (trim($value) === '') {
                continue;
            }

            $rows[] = ['line' => $line, 'value' => $value];
        }

        if ($column === null) {
            throw new LocalizedException(__('The file is empty.'));
        }

        return $rows;
    }

    private function resolveColumn(array $firstRow): array
    {
        foreach ($firstRow as $index => $cell) {
            $key = strtolower(trim((string)$cell));
            $key = trim($key, "\"' ");
            if (isset(self::EAN_HEADERS[$key])) {
                return [(int)$index, true];
            }
        }

        $first = trim((string)($firstRow[0] ?? ''));

        return [0, $first !== '' && !preg_match('/\d/', $first)];
    }

    private function hasContent(array $cells): bool
    {
        foreach ($cells as $cell) {
            if (trim((string)$cell) !== '') {
                return true;
            }
        }

        return false;
    }
}
