<?php

declare(strict_types=1);

namespace PortalPeople\upn\services;

use PortalPeople\shippingcosts\models\ColumnMapForm;
use PortalPeople\shippingcosts\services\MarkdownTableParser;

/** Converts structured UPN Markdown tables into importer rows. */
final class UpnMarkdownParser
{
    private readonly MarkdownTableParser $tables;

    public function __construct(?MarkdownTableParser $tables = null)
    {
        $this->tables = $tables ?? new MarkdownTableParser();
    }

    /** @return list<array<string, mixed>> */
    public function parse(string $markdown, string $provider = 'UPN'): array
    {
        $rows = $this->tables->parse($markdown, ['Zone', 'Service', 'PostCode']);
        $result = [];

        foreach ($rows as $row) {
            if (trim($row['Zone'] ?? '') === '' || trim($row['PostCode'] ?? '') === '') {
                continue;
            }

            $result[] = [
                'Provider' => $provider,
                'Zone' => trim($row['Zone']),
                'Service' => ColumnMapForm::normalizeType($row['Service'] ?? ''),
                'TransitTime' => trim($row['TransitTime'] ?? ''),
                'PostCode' => trim($row['PostCode']),
                'Micro' => $this->price($row['Micro'] ?? ''),
                'Quarter' => $this->price($row['Quarter'] ?? ''),
                'Qtr+' => $this->price($row['Qtr+'] ?? ''),
                'Half' => $this->price($row['Half'] ?? ''),
                'Euro' => $this->price($row['Euro'] ?? ''),
                'Full' => $this->price($row['Full'] ?? ''),
            ];
        }

        return $result;
    }

    private function price(string $value): float|string
    {
        $value = trim($value);
        if ($value === '') {
            return '';
        }

        $value = preg_replace('/[^0-9.\-]/', '', $value) ?? '';
        return $value === '' ? '' : (float) $value;
    }
}
