<?php

declare(strict_types=1);

namespace Dealerdirect\Agreements\Utils;

use DealerDirect\Generic\Category\Driveable;

final class CommentsFormatter
{
    private const DRIVABLE_CHECKS = [
        'Ist das Motorrad fahrtüchtig?' => [
            'Ja' => Driveable::YES,
            'Nein' => Driveable::NO,
        ],
        'Start de motor?' => [
            'Ja' => Driveable::YES,
            'Nee' => Driveable::NO,
        ],
    ];

    public function __construct(
        private string $internalComment,
        private string $consumerComment,
    ) {
    }

    /**
     * @return array<string,null|int|string>
     */
    public function format(): array
    {
        $vin = null;
        $drivable = Driveable::UNKNOWN;
        $consumerComment = $this->consumerComment;
        $internalComment = $this->internalComment;

        foreach (self::DRIVABLE_CHECKS as $drivableCheck => $values) {
            if (str_contains($internalComment, $drivableCheck)) {
                foreach ($values as $value => $result) {
                    $check = "{$drivableCheck}: {$value}";
                    if (str_contains($internalComment, $check)) {
                        $drivable = $result;
                        $internalComment = str_replace($check, '', $internalComment);

                        break;
                    }
                }
            }
        }

        if (str_contains($internalComment, 'VIN:')) {
            foreach (preg_split("/((\r?\n)|(\r\n?))/", $internalComment) as $line) {
                if (!str_contains($line, 'VIN:')) {
                    continue;
                }

                $internalComment = str_replace($line, '', $internalComment);
                $vin = trim(str_replace('VIN:', '', $line));

                break;
            }
        }

        return [
            'vin' => $vin,
            'drivable' => $drivable,
            'internal_comments' => trim($internalComment),
            'consumer_comments' => trim($consumerComment),
        ];
    }
}
