<?php

namespace App\Support;

use App\Models\LaundrySaleProduct;

/**
 * Reglas de negocio: solo tipo «producto» puede llevar inventario POS (existencias por pieza).
 */
final class LaundrySaleProductTipoRules
{
    /**
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    public static function normalizeForPersist(array $data, ?LaundrySaleProduct $existing = null): array
    {
        $tipo = $data['tipo'] ?? $existing?->tipo ?? LaundrySaleProduct::TIPO_SERVICIO;
        $billing = $data['billing_unit'] ?? $existing?->billing_unit ?? LaundrySaleProduct::BILLING_UNIT_PIECE;

        if ($tipo === LaundrySaleProduct::TIPO_SERVICIO) {
            $data['tracks_stock'] = false;
            $data['inventory_product_id'] = null;
            $data['stock_quantity'] = null;

            return $data;
        }

        if ($billing !== LaundrySaleProduct::BILLING_UNIT_PIECE) {
            $data['tracks_stock'] = false;
            $data['stock_quantity'] = null;

            return $data;
        }

        if (array_key_exists('tracks_stock', $data) && ! (bool) $data['tracks_stock']) {
            $data['stock_quantity'] = null;
        }

        return $data;
    }

    public static function tracksStockAllowed(string $tipo, string $billingUnit, bool $tracksStock): bool
    {
        return $tipo === LaundrySaleProduct::TIPO_PRODUCTO
            && $billingUnit === LaundrySaleProduct::BILLING_UNIT_PIECE
            && $tracksStock;
    }
}
