/*
 * This file is part of LibEuFin.
 * Copyright (C) 2024-2025 Taler Systems S.A.

 * LibEuFin is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation; either version 3, or
 * (at your option) any later version.

 * LibEuFin 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 Affero General
 * Public License for more details.

 * You should have received a copy of the GNU Affero General Public
 * License along with LibEuFin; see the file COPYING.  If not, see
 * <http://www.gnu.org/licenses/>
 */

import kotlinx.coroutines.runBlocking
import org.junit.Test
import tech.libeufin.common.db.*
import kotlin.io.path.Path
import kotlin.io.path.readText
import java.util.UUID
import kotlin.test.assertTrue

class MigrationTest {
    @Test
    fun test() = runBlocking {
        val conn = pgDataSource("postgres:///libeufincheck").pgConnection()

        // Drop current schemas
        conn.execSQLUpdate(Path("../database-versioning/libeufin-bank-drop.sql").readText())
        conn.execSQLUpdate(Path("../database-versioning/libeufin-nexus-drop.sql").readText())

        // libeufin-bank-0001
        conn.execSQLUpdate(Path("../database-versioning/libeufin-bank-0001.sql").readText())
        conn.execSQLUpdate("""
            INSERT INTO customers (login, password_hash) VALUES
                ('account_1', 'fack_hash'),
                ('account_2', 'fack_hash'),
                ('account_3', 'fack_hash'),
                ('account_4', 'fack_hash');
            INSERT INTO bank_accounts (internal_payto_uri, owning_customer_id) VALUES
                ('payto_1', 1),
                ('payto_2', 2),
                ('payto_3', 3),
                ('payto_4', 4);
            INSERT INTO bank_account_transactions(creditor_payto_uri, creditor_name, debtor_payto_uri, debtor_name, subject, amount, transaction_date, direction, bank_account_id) VALUES
                ('payto_1', 'account_1', 'payto_2', 'account_2', 'subject', (0, 0)::taler_amount, 42, 'credit'::direction_enum, 1),
                ('payto_1', 'account_1', 'payto_2', 'account_2', 'subject', (0, 0)::taler_amount, 42, 'credit'::direction_enum, 1),
                ('payto_1', 'account_1', 'payto_2', 'account_2', 'subject', (0, 0)::taler_amount, 42, 'credit'::direction_enum, 1);
            INSERT INTO taler_exchange_incoming(reserve_pub, bank_transaction) VALUES
                ('\x6ca1ab1a76a484d7424064c51c49c1947405f42f7d185d052dbf6718d845ec6b'::bytea, 1),
                ('\xa605637a4852684e4957e6177f41311eacf8661a6a74b90178c487fe347b9918'::bytea, 2);
            INSERT INTO challenges(code, creation_date, expiration_date, retry_counter) VALUES
                ('secret_code', 42, 42, 42),
                ('secret_code', 42, 42, 42);
            INSERT INTO cashout_operations(request_uid, amount_debit, amount_credit, subject, creation_time, bank_account, challenge, local_transaction) VALUES
                ('\x6ca1ab1a76a484d7424064c51c49c1947405f42f7d185d052dbf6718d845ec6b'::bytea, (0, 0)::taler_amount, (0, 0)::taler_amount, 'subject', 42, 1, 1, 1),
                ('\xa605637a4852684e4957e6177f41311eacf8661a6a74b90178c487fe347b9918'::bytea, (0, 0)::taler_amount, (0, 0)::taler_amount, 'subject', 42, 1, 2, NULL);
            INSERT INTO taler_withdrawal_operations(withdrawal_uuid, amount, reserve_pub, wallet_bank_account) VALUES
                (gen_random_uuid(), (0, 0)::taler_amount, '\x6ca1ab1a76a484d7424064c51c49c1947405f42f7d185d052dbf6718d845ec6b'::bytea, 1),
                (gen_random_uuid(), (0, 0)::taler_amount, '\xa605637a4852684e4957e6177f41311eacf8661a6a74b90178c487fe347b9918'::bytea, 2);
        """)

        // libeufin-bank-0002
        conn.execSQLUpdate(Path("../database-versioning/libeufin-bank-0002.sql").readText())

        // libeufin-bank-0003
        conn.execSQLUpdate(Path("../database-versioning/libeufin-bank-0003.sql").readText())

        // libeufin-bank-0004
        conn.execSQLUpdate(Path("../database-versioning/libeufin-bank-0004.sql").readText())

        conn.execSQLUpdate("""
            UPDATE bank_accounts SET min_cashout=(0, 1) WHERE bank_account_id=2;
            UPDATE bank_accounts SET min_cashout=(2, 300) WHERE bank_account_id IN (3, 4);
        """)

        // libeufin-bank-0005
        conn.execSQLUpdate(Path("../database-versioning/libeufin-bank-0005.sql").readText())

        // libeufin-bank-0006
        conn.execSQLUpdate(Path("../database-versioning/libeufin-bank-0006.sql").readText())

        // libeufin-bank-0007
        conn.execSQLUpdate(Path("../database-versioning/libeufin-bank-0007.sql").readText())

        // libeufin-bank-0008
        conn.execSQLUpdate(Path("../database-versioning/libeufin-bank-0008.sql").readText())

        // libeufin-bank-0009
        conn.execSQLUpdate(Path("../database-versioning/libeufin-bank-0009.sql").readText())

        // libeufin-bank-0010
        conn.execSQLUpdate(Path("../database-versioning/libeufin-bank-0010.sql").readText())

        // libeufin-bank-0011
        conn.execSQLUpdate(Path("../database-versioning/libeufin-bank-0011.sql").readText())

        // libeufin-bank-0012
        conn.execSQLUpdate(Path("../database-versioning/libeufin-bank-0012.sql").readText())

        conn.execSQLUpdate("""
            INSERT INTO config(key, value) VALUES
                ('cashin_ratio', '{"val": 1, "frac": 2}'::jsonb),
                ('cashin_fee', '{"val": 3, "frac": 4}'::jsonb),
                ('cashin_tiny_amount', '{"val": 5, "frac": 6}'::jsonb),
                ('cashin_min_amount', '{"val": 7, "frac": 8}'::jsonb),
                ('cashin_rounding_mode', '{"mode": "zero"}'::jsonb),
                ('cashout_ratio', '{"val": 9, "frac": 10}'::jsonb),
                ('cashout_fee', '{"val": 11, "frac": 12}'::jsonb),
                ('cashout_tiny_amount', '{"val": 13, "frac": 14}'::jsonb),
                ('cashout_min_amount', '{"val": 15, "frac": 16}'::jsonb),
                ('cashout_rounding_mode', '{"mode": "nearest"}'::jsonb);
        """)

        // libeufin-bank-0013
        conn.execSQLUpdate(Path("../database-versioning/libeufin-bank-0013.sql").readText())
        conn.withStatement(
            """
            SELECT value='{
                "cashin": {
                    "fee": {
                        "val": 3,
                        "frac": 4
                    },
                    "ratio": {
                        "val": 1,
                        "frac": 2
                    }, 
                    "min_amount": {
                        "val": 7, 
                        "frac": 8
                    }, 
                    "tiny_amount": {
                        "val": 5, 
                        "frac": 6
                    }, 
                    "rounding_mode": "zero"
                }, 
                "cashout": {
                    "fee": {
                        "val": 11, 
                        "frac": 12
                    }, 
                    "ratio": {
                        "val": 9, 
                        "frac": 10
                    }, 
                    "min_amount": {
                        "val": 15, 
                        "frac": 16
                    }, 
                    "tiny_amount": {
                        "val": 13, 
                        "frac": 14
                    }, 
                    "rounding_mode": "nearest"
                }
            }'::jsonb FROM libeufin_bank.config WHERE key='conversion_rate'
            """
        ) {
            one {
                assertTrue(it.getBoolean(1))
            }
        }

        // libeufin-nexus-0001
        conn.execSQLUpdate(Path("../database-versioning/libeufin-nexus-0001.sql").readText())
        conn.execSQLUpdate("""
            INSERT INTO outgoing_transactions(amount, execution_time, message_id) VALUES
                ((0, 0)::taler_amount, 42, 'id');
            INSERT INTO initiated_outgoing_transactions(amount, wire_transfer_subject, initiation_time, credit_payto_uri, outgoing_transaction_id, request_uid) VALUES
                ((0, 0)::taler_amount, 'subject', 42, 'payto_0', 1, 'request_uid');
        """)

        // libeufin-nexus-0002
        conn.execSQLUpdate(Path("../database-versioning/libeufin-nexus-0002.sql").readText())

        // libeufin-nexus-0003
        conn.execSQLUpdate(Path("../database-versioning/libeufin-nexus-0003.sql").readText())

        // libeufin-nexus-0004
        conn.execSQLUpdate(Path("../database-versioning/libeufin-nexus-0004.sql").readText())

        // libeufin-nexus-0005
        conn.execSQLUpdate(Path("../database-versioning/libeufin-nexus-0005.sql").readText())

        // libeufin-nexus-0006
        conn.execSQLUpdate(Path("../database-versioning/libeufin-nexus-0006.sql").readText())

        conn.execSQLUpdate("""
            INSERT INTO initiated_outgoing_transactions(amount, wire_transfer_subject, initiation_time, credit_payto_uri, outgoing_transaction_id, request_uid, order_id) VALUES
                ((42, 0)::taler_amount, 'subject', 0, 'credit_payto', NULL, 'TX0', 'ORDER0'),
                ((41, 0)::taler_amount, 'subject', 0, 'credit_payto', NULL, 'TX1', NULL);
        """)

        // libeufin-nexus-0007
        conn.execSQLUpdate(Path("../database-versioning/libeufin-nexus-0007.sql").readText())

        // libeufin-nexus-0008
        conn.execSQLUpdate(Path("../database-versioning/libeufin-nexus-0008.sql").readText())

        // libeufin-nexus-0009
        conn.execSQLUpdate(Path("../database-versioning/libeufin-nexus-0009.sql").readText())

        conn.execSQLUpdate("""
            INSERT INTO incoming_transactions(amount, subject, execution_time, debit_payto, bank_id) VALUES
                ((1, 0)::taler_amount, 'simple', 42, 'debit_payto', 'first'),
                ((2, 0)::taler_amount, 'reserve', 42, 'debit_payto', 'second'),
                ((3, 0)::taler_amount, 'kyc', 42, 'debit_payto', 'third'),
                ((4, 0)::taler_amount, 'simple', 42, 'debit_payto', '${UUID.randomUUID()}'),
                ((5, 0)::taler_amount, 'reserve', 42, 'debit_payto', '${UUID.randomUUID()}'),
                ((6, 0)::taler_amount, 'kyc', 42, 'debit_payto', '${UUID.randomUUID()}');;
            INSERT INTO talerable_incoming_transactions(incoming_transaction_id, type, reserve_public_key, account_pub) VALUES
                (2, 'reserve', '\x6ca1ab1a76a484d7424064c51c49c1947405f42f7d185d052dbf6718d845ec6b'::bytea, null),
                (3, 'kyc', null, '\x6ca1ab1a76a484d7424064c51c49c1947405f42f7d185d052dbf6718d845ec6b'::bytea);
        """)

        // libeufin-nexus-0010
        conn.execSQLUpdate(Path("../database-versioning/libeufin-nexus-0010.sql").readText())

        // libeufin-nexus-0011
        conn.execSQLUpdate(Path("../database-versioning/libeufin-nexus-0011.sql").readText())
    }
}