-- ============================================================
-- 赠送卡细分数据一致性验证脚本
-- 用途：ETL 跑数完成后，验证 DWS 层赠送卡细分字段的数据正确性
-- 关联需求：Requirements 10.1, 10.2, 10.3
-- ============================================================

-- ------------------------------------------------------------
-- 1. 验证余额恒等式 (Requirement 10.3)
--    gift_card_balance = gift_liquor_balance + gift_table_fee_balance + gift_voucher_balance
--    预期结果：空集（无违反恒等式的记录）
-- ------------------------------------------------------------
SELECT site_id, stat_date,
       gift_card_balance,
       gift_liquor_balance + gift_table_fee_balance + gift_voucher_balance AS sum_breakdown,
       gift_card_balance - (gift_liquor_balance + gift_table_fee_balance + gift_voucher_balance) AS diff
FROM dws.dws_finance_recharge_summary
WHERE gift_card_balance != gift_liquor_balance + gift_table_fee_balance + gift_voucher_balance;

-- ------------------------------------------------------------
-- 2. 验证新增恒等式 (Requirement 10.2 隐含)
--    recharge_gift = gift_liquor_recharge + gift_table_fee_recharge + gift_voucher_recharge
--    预期结果：空集（无违反恒等式的记录）
-- ------------------------------------------------------------
SELECT site_id, stat_date,
       recharge_gift,
       gift_liquor_recharge + gift_table_fee_recharge + gift_voucher_recharge AS sum_breakdown,
       recharge_gift - (gift_liquor_recharge + gift_table_fee_recharge + gift_voucher_recharge) AS diff
FROM dws.dws_finance_recharge_summary
WHERE recharge_gift != gift_liquor_recharge + gift_table_fee_recharge + gift_voucher_recharge;

-- ------------------------------------------------------------
-- 3. 验证 DWS 与 DWD 源数据一致 (Requirement 10.1)
--    DWS 各类型余额 = DWD dim_member_card_account 对应 card_type_id 的 balance 之和
--    预期结果：DWS 行与 DWD 行的 liquor/table_fee/voucher 数值一致
--    card_type_id 映射：
--      2794699703437125 → 酒水卡 (liquor)
--      2791990152417157 → 台费卡 (table_fee)
--      2793266846533445 → 抵用券 (voucher)
-- ------------------------------------------------------------
SELECT 'DWS' AS source,
       SUM(gift_liquor_balance) AS liquor,
       SUM(gift_table_fee_balance) AS table_fee,
       SUM(gift_voucher_balance) AS voucher
FROM dws.dws_finance_recharge_summary
WHERE stat_date = CURRENT_DATE
UNION ALL
SELECT 'DWD',
       SUM(CASE WHEN card_type_id = 2794699703437125 THEN balance ELSE 0 END),
       SUM(CASE WHEN card_type_id = 2791990152417157 THEN balance ELSE 0 END),
       SUM(CASE WHEN card_type_id = 2793266846533445 THEN balance ELSE 0 END)
FROM dwd.dim_member_card_account
WHERE scd2_is_current = 1 AND COALESCE(is_delete, 0) = 0
  AND card_type_id IN (2794699703437125, 2791990152417157, 2793266846533445);
