#!/bin/bash
source $HOME/.gamerc

[ "$1" == "" ] && exec echo "Usage: $0 <Environment (TEST => 0, LIVE => 1)>"

env=$1
correct_filename="/tmp/itemmall_item_price_iap_name_mapping_correct_others_monitor.log"
output_filename="/tmp/itemmall_item_price_iap_name_others_monitor.log"

psql -U postgres ${ACCOUNT_DB_NAME} -c "WITH t1 AS (SELECT id, iap_name_other, (string_to_array(iap_name_other, '_'))[array_length(string_to_array(iap_name_other, '_'), 1)] AS last_value, price FROM itemmall_item WHERE iap_name_other <> '' ORDER BY id), t2 AS (SELECT last_value, price, COUNT(*) FROM t1 GROUP BY last_value, price ORDER BY last_value::INTEGER, count DESC) INSERT INTO xl_iap_name_price_mapping SELECT DISTINCT ON (last_value::INTEGER) last_value, price FROM t2 WHERE (last_value, price) NOT IN (SELECT last_value, price FROM xl_iap_name_price_mapping) ORDER BY last_value::INTEGER, count DESC;"

COUNT=$(psql -U postgres ${ACCOUNT_DB_NAME} -c "COPY (WITH t1 AS (SELECT id, iap_name_other, (string_to_array(iap_name_other, '_'))[array_length(string_to_array(iap_name_other, '_'), 1)] AS last_value, price FROM itemmall_item WHERE iap_name_other <> '' ORDER BY id) SELECT COUNT(*) FROM t1 WHERE (last_value, price) NOT IN (SELECT last_value, price FROM xl_iap_name_price_mapping)) TO STDOUT;")

if [ "${COUNT}" -ne 0 ]; then
    CORRECT=$(psql -U postgres ${ACCOUNT_DB_NAME} -c "COPY (SELECT * FROM xl_iap_name_price_mapping ORDER BY last_value::INTEGER) TO '${correct_filename}' CSV HEADER")
    OUTPUT=$(psql -U postgres ${ACCOUNT_DB_NAME} -c "COPY (WITH t1 AS (SELECT id, iap_name_other, iap_name_ios, iap_name_xpay_h5, iap_name_other, (string_to_array(iap_name_other, '_'))[array_length(string_to_array(iap_name_other, '_'), 1)] AS last_value, price FROM itemmall_item WHERE iap_name_other <> '' ORDER BY id) SELECT * FROM t1 WHERE (last_value, price) NOT IN (SELECT last_value, price FROM xl_iap_name_price_mapping) ORDER BY last_value::INTEGER, price) TO '${output_filename}' CSV HEADER")

    if [ "${env}" == "0" ]; then
        ENV_TAG="(測試)"
    elif [ "${env}" == "1" ]; then
        ENV_TAG="(正式)"
    fi
    send_messages_test REFERENCE itemmall_item_price_iap_name_mapping_correct_others "${ENV_TAG} 上架表 IAP_NAME 跟價錢對應 (第三方), 正確版本如下"
    send_messages_test ERROR itemmall_item_price_iap_name_others "${ENV_TAG} 上架表 IAP_NAME 跟價錢對應有誤 (第三方), 請確認!"
fi
