using System;

namespace HydraulicSimulator.Models
{
    /// <summary>
    /// Válvula por Kv con apertura 0..1
    /// </summary>
    public class ValveKv : Element
    {
        public double KvFull { get; set; } // m³/h / sqrt(bar) a 100%
        public double Opening { get; set; } // 0..1

        public ValveKv(double kvFull, double opening)
        {
            KvFull = kvFull;
            Opening = opening;
        }

        private double KvEff
        {
            get
            {
                var x = Math.Min(1.0, Math.Max(0.0, Opening));
                return Math.Max(1e-6, KvFull * x); // lineal simple y evita 0
            }
        }

        public override double Dp(double q, Fluid fluid)
        {
            var kv = KvEff;
            var qh = q * 3600.0; // m³/h
            var dpBar = Math.Pow(qh / kv, 2); // bar (SG≈1)
            var dpPa = dpBar * 1e5;
            return Math.Sign(q) * Math.Abs(dpPa);
        }

        public override double DdpDq(double q, Fluid fluid)
        {
            var kv = KvEff;
            var coeff = 2.0 * 1e5 * Math.Pow(3600.0 / kv, 2);
            return coeff * Math.Abs(q) + 1e-12;
        }
    }
}
