--
-- 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 merchant-0026.sql
-- @brief add hashes for product images
-- @author Bohdan Potuzhnyi, Florian Dold
-- Release: v1.2.0


BEGIN;

-- Check patch versioning is in place.
SELECT _v.register_patch('merchant-0026', NULL, NULL);

SET search_path TO public;

CREATE EXTENSION IF NOT EXISTS pgcrypto;

-- Was created by merchant-0025.sql
ALTER EXTENSION pgcrypto SET SCHEMA public;
ALTER EXTENSION pg_trgm SET SCHEMA public;

SET search_path TO merchant, public;

ALTER TABLE merchant_inventory
  ADD COLUMN image_hash TEXT;

COMMENT ON COLUMN merchant_inventory.image_hash
  IS 'SHA-256 hash of the base64-encoded image data, used by wallets to fetch product images.';

ALTER TABLE merchant_inventory
    DISABLE TRIGGER trigger_inventory_changes;

UPDATE merchant_inventory
   SET image_hash = CASE
                      WHEN (image IS NULL) OR (image = '')
                      THEN NULL
                      ELSE encode(
                             digest(
                               convert_to(image, 'UTF8'),
                               'sha256'
                             ),
                             'hex'
                           )
                    END;

ALTER TABLE merchant_inventory
    ENABLE TRIGGER trigger_inventory_changes;

CREATE INDEX merchant_inventory_by_image_hash
  ON merchant_inventory
    (merchant_serial, image_hash);

COMMIT;
