--
-- 0022-shop-init.sql
--
-- #22 - stored function for initializing Shop.py
--
-- ISC License
--
-- Copyright 2023-2025 Brmlab, z.s.
-- TMA <tma+hs@jikos.cz>
--
-- Permission to use, copy, modify, and/or distribute this software
-- for any purpose with or without fee is hereby granted, provided
-- that the above copyright notice and this permission notice appear
-- in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
-- WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
-- AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
-- CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
-- OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
-- NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
-- CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--

-- To require fully-qualified names
SELECT pg_catalog.set_config('search_path', '', false);

DO $upgrade_block$
DECLARE
	v INTEGER;
BEGIN

IF brmbar_privileged.has_exact_schema_version(21) THEN


SELECT COUNT(1) INTO v
	FROM pg_catalog.pg_type typ
	INNER JOIN pg_catalog.pg_namespace nsp
	ON nsp.oid = typ.typnamespace
	WHERE nsp.nspname = 'brmbar_privileged'
	AND typ.typname='shop_class_initialization_data_type';

IF v>0 THEN
	RAISE NOTICE 'Changing type shop_class_initialization_data_type';
	DROP TYPE brmbar_privileged.shop_class_initialization_data_type CASCADE;
ELSE
	RAISE NOTICE 'Creating type shop_class_initialization_data_type';
END IF;

CREATE TYPE brmbar_privileged.shop_class_initialization_data_type
AS (
	currency_id INTEGER, --public.currencies.id%TYPE,
	profits_id INTEGER, --public.accounts.id%TYPE,
	cash_id INTEGER, --public.accounts.id%TYPE,
	excess_id INTEGER, --public.accounts.id%TYPE,
	deficit_id INTEGER --public.accounts.id%TYPE
);

CREATE OR REPLACE FUNCTION public.shop_class_initialization_data()
RETURNS brmbar_privileged.shop_class_initialization_data_type
LANGUAGE plpgsql
AS
$$
DECLARE
	rv brmbar_privileged.shop_class_initialization_data_type;
BEGIN
	rv.currency_id := 1;
	SELECT id INTO rv.profits_id FROM public.accounts WHERE name = 'BrmBar Profits';
	SELECT id INTO rv.cash_id FROM public.accounts WHERE name = 'BrmBar Cash';
	SELECT id INTO rv.excess_id FROM public.accounts WHERE name = 'BrmBar Excess';
	SELECT id INTO rv.deficit_id FROM public.accounts WHERE name = 'BrmBar Deficit';
	RETURN rv;
END;
$$;


PERFORM brmbar_privileged.upgrade_schema_version_to(22);
END IF;

END;
$upgrade_block$;

-- vim: set ft=plsql :

