--
-- This file is part of TALER
-- Copyright (C) 2023-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/>

DROP FUNCTION IF EXISTS exchange_do_get_kyc_rules;

CREATE FUNCTION exchange_do_get_kyc_rules(
  IN in_h_payto BYTEA,
  IN in_now INT8,
  IN in_merchant_pub BYTEA, -- possibly NULL
  OUT out_target_pub BYTEA, -- possibly NULL
  OUT out_reserve_pub BYTEA, -- possibly NULL
  OUT out_jnew_rules JSONB -- possibly NULL
 )
LANGUAGE plpgsql
AS $$
DECLARE
  my_found BOOL;
BEGIN
  IF in_merchant_pub IS NOT NULL
  THEN
    PERFORM FROM reserves_in
      WHERE reserve_pub=in_merchant_pub
        AND wire_source_h_payto IN
         (SELECT wire_target_h_payto
            FROM wire_targets
           WHERE h_normalized_payto = in_h_payto);
    my_found = FOUND;
  ELSE
    my_found = FALSE;
  END IF;
  IF FOUND
  THEN
    -- The merchant_pub used by the client matches, use that
    out_reserve_pub = in_merchant_pub;
  ELSE
    -- If multiple reserves_in match, we pick the latest one
    SELECT reserve_pub
      INTO out_reserve_pub
      FROM reserves_in
     WHERE wire_source_h_payto IN
      (SELECT wire_target_h_payto
         FROM wire_targets
        WHERE h_normalized_payto = in_h_payto)
     ORDER BY execution_date DESC
     LIMIT 1;
  END IF;

  SELECT target_pub
    INTO out_target_pub
    FROM kyc_targets
   WHERE h_normalized_payto = in_h_payto;

  SELECT jnew_rules
    INTO out_jnew_rules
    FROM legitimization_outcomes
   WHERE h_payto = in_h_payto
     AND COALESCE(expiration_time >= $2, TRUE)
     AND COALESCE(is_active, TRUE)
   -- technically only one should ever be active, but we can be conservative
   ORDER BY expiration_time DESC
   LIMIT 1;


END $$;
