DROP FUNCTION IF EXISTS dbo.fn_GetPaidServiceCurrentCost;

CREATE FUNCTION dbo.fn_GetPaidServiceCurrentCost(
    "MedicalServiceID" uuid,
    "OnDate" timestamp,
    "CostCategory" uuid,
    "Lpu" uuid
)
    RETURNS numeric(12, 2) AS
$$
DECLARE
    ret  numeric(12, 2);
        Lpu1 uuid;
        Lpu2 uuid;
        rc   integer;
BEGIN
    IF "OnDate" IS NULL THEN
        "OnDate" := CURRENT_TIMESTAMP;
    END IF;

    CREATE TEMPORARY TABLE Costs
        (
            id      SERIAL,
            cost    numeric(12, 2),
            LpuMain uuid
        ) ON COMMIT DROP;
    
    INSERT INTO Costs(cost, LpuMain)
    SELECT psc.Cost, psc.LpuMain
    FROM AKUZ.T_PAID_SERVICE_COST psc
    WHERE psc.medicalservice = "MedicalServiceID"
      AND psc.Date <= "OnDate"
      AND (psc.DateEnd >= "OnDate" OR psc.DateEnd IS NULL)
      AND (psc.LpuMain = "Lpu" OR psc.LpuMain IS NULL)
      AND psc.costcategory = "CostCategory"
    ORDER BY psc.LpuMain DESC, psc.Date DESC
    LIMIT 2;
    
    GET DIAGNOSTICS rc = ROW_COUNT;
    
    SELECT c.cost, c.LpuMain
    INTO ret, Lpu1
    FROM Costs c
    WHERE c.id = 1;
    
    SELECT c.LpuMain
    INTO Lpu2
    FROM Costs c
    WHERE c.id = 2;
    
    IF rc = 0 THEN
        RETURN -1;
    END IF;
    
    IF Lpu2 IS NOT NULL OR (Lpu1 IS NULL AND rc = 2) THEN
        RETURN -2;
    END IF;
        
    RETURN ret;
END;
$$
LANGUAGE plpgsql;