<?php

namespace App\Support;

use App\Models\Etapa;
use App\Models\TipoServicio;

/**
 * Inferencia de etapa (proceso) y servicio (SLA) desde nombres del sistema anterior.
 */
final class TibuLegacyCatalogMapper
{
    public static function resolveEtapaCode(string $productName, string $categoryName): string
    {
        $n = self::upper($productName);
        $c = self::upper($categoryName);

        if (self::containsAny($n, ['LAVADO Y PLANCHADO', 'LAVADO/PLANCHADO']) || self::containsAny($c, ['LAVADO Y PLANCHADO'])) {
            return Etapa::CODE_COMPLETO;
        }

        if (self::containsAny($n, ['PLANCHADO', 'PLANCHA']) || self::containsAny($c, ['PLANCHADO', 'MANTEL'])) {
            return Etapa::CODE_PLANCHADO;
        }

        if (self::containsAny($n, ['LAVADO', 'LAVAR', 'SECADO', 'TINTOR']) || self::containsAny($c, ['SECADO', 'TINTOR', 'LAVADO DE ROPA'])) {
            return Etapa::CODE_LAVADO;
        }

        if (self::containsAny($c, ['INSUMO', 'BAÑO', 'ALMOHADA', 'SÁBANA', 'SABANA', 'EDREDON', 'MOCHILA', 'HAMACA', 'PELUCHE', 'GANCHO'])) {
            return Etapa::CODE_VENTA;
        }

        return Etapa::CODE_COMPLETO;
    }

    public static function resolveTipoServicioCode(string $productName, string $categoryName): string
    {
        $n = self::upper($productName);
        $c = self::upper($categoryName);

        if (self::containsAny($n, ['SUPER EXPRESS', 'SUPER-EXPRESS', 'URGENTE']) || self::containsAny($c, ['URGENTE'])) {
            return TipoServicio::CODE_URGENT;
        }

        if (self::containsAny($n, ['EXPRESS'])) {
            return TipoServicio::CODE_EXPRESS;
        }

        return TipoServicio::CODE_NORMAL;
    }

    public static function resolveBillingUnit(string $productName, string $categoryName): string
    {
        $n = self::upper($productName);
        $c = self::upper($categoryName);

        if (self::containsAny($n, ['KG', 'KILO', 'KILOGRAMO']) || self::containsAny($c, ['CARGA'])) {
            return 'kg';
        }

        return 'piece';
    }

    private static function upper(string $value): string
    {
        return mb_strtoupper(trim($value), 'UTF-8');
    }

  /**
   * @param  list<string>  $needles
   */
    private static function containsAny(string $haystack, array $needles): bool
    {
        foreach ($needles as $needle) {
            if ($needle !== '' && str_contains($haystack, $needle)) {
                return true;
            }
        }

        return false;
    }
}
