<?php

declare(strict_types=1);

namespace PortalPeople\palletforce\services;

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

/** Converts structured Palletforce Markdown tables into importer rows. */
final class PalletforceMarkdownParser
{
    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 = 'Palletforce'): array
    {
        $rows = $this->tables->parse($markdown, ['Band', 'PostCode', 'Service']);
        $result = [];

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

            $result[] = [
                'Provider' => $provider,
                'Band' => trim($row['Band']),
                'PostCode' => trim($row['PostCode']),
                'Service' => ColumnMapForm::normalizeType($row['Service'] ?? ''),
                'Qtr' => $this->price($row['Qtr'] ?? ''),
                'Half' => $this->price($row['Half'] ?? ''),
                'Full' => $this->price($row['Full'] ?? ''),
                '2' => $this->price($row['2'] ?? ''),
                '3' => $this->price($row['3'] ?? ''),
                '4' => $this->price($row['4'] ?? ''),
                '5' => $this->price($row['5'] ?? ''),
                '5+ per pallet' => $this->price($row['5+ per pallet'] ?? ''),
                'requires_review' => $this->hasPoa($row),
            ];
        }

        return $result;
    }

    /** @param array<string, string> $row */
    private function hasPoa(array $row): bool
    {
        foreach (['Qtr', 'Half', 'Full', '2', '3', '4', '5', '5+ per pallet'] as $column) {
            if (stripos($row[$column] ?? '', 'p.o.a') !== false || stripos($row[$column] ?? '', 'poa') !== false) {
                return true;
            }
        }

        return false;
    }

    private function price(string $value): float|string
    {
        $value = trim($value);
        if ($value === '' || stripos($value, 'p.o.a') !== false || stripos($value, 'poa') !== false) {
            return '';
        }

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