--
-- This file is part of TALER
-- Copyright (C) 2025 Taler Systems SA
--
-- TALER is free software; you can redistribute it and/or modify it under the
-- terms of the GNU General Public License as published by the Free Software
-- Foundation; either version 3, or (at your option) any later version.
--
-- TALER is distributed in the hope that it will be useful, but WITHOUT ANY
-- WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-- A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License along with
-- TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>

-- @file insert_unit.sql
-- @brief SQL for inserting units
-- @author Bohdan Potuzhnyi

DROP FUNCTION IF EXISTS merchant_do_insert_unit;
CREATE FUNCTION merchant_do_insert_unit (
    IN in_unit TEXT,
    IN in_unit_name_long TEXT,
    IN in_unit_name_short TEXT,
    IN in_unit_name_long_i18n BYTEA,
    IN in_unit_name_short_i18n BYTEA,
    IN in_unit_allow_fraction BOOL,
    IN in_unit_precision_level INT4,
    IN in_unit_active BOOL,
    OUT out_conflict BOOL,
    OUT out_unit_serial INT8)
    LANGUAGE plpgsql
AS $$
BEGIN
    -- Reject attempts to shadow builtin identifiers.
    IF EXISTS (
        SELECT 1
           FROM merchant.merchant_builtin_units bu
          WHERE bu.unit = in_unit
    ) THEN
        out_conflict := TRUE;
        out_unit_serial := NULL;
        RETURN;
    END IF;

    INSERT INTO merchant_custom_units (
        unit,
        unit_name_long,
        unit_name_short,
        unit_name_long_i18n,
        unit_name_short_i18n,
        unit_allow_fraction,
        unit_precision_level,
        unit_active)
    VALUES (
               in_unit,
               in_unit_name_long,
               in_unit_name_short,
               in_unit_name_long_i18n,
               in_unit_name_short_i18n,
               in_unit_allow_fraction,
               in_unit_precision_level,
               in_unit_active)
    ON CONFLICT (unit)
       DO NOTHING
    RETURNING unit_serial
         INTO out_unit_serial;

    IF FOUND THEN
        out_conflict := FALSE;
        RETURN;
    END IF;

    -- Conflict: custom unit already exists.
    SELECT unit_serial
    INTO out_unit_serial
    FROM merchant_custom_units
    WHERE unit = in_unit;

    out_conflict := TRUE;
END $$;
