-- Idempotent migration / diagnostic script
-- Ensures `fees` has discount columns, backfills from `fee_discounts` if present,
-- and provides diagnostic queries to help investigate why discounts weren't persisted.

START TRANSACTION;

-- Add columns if missing (MySQL/MariaDB 10.3+/8+ support IF NOT EXISTS)
ALTER TABLE `fees`
  ADD COLUMN IF NOT EXISTS `original_amount` DECIMAL(12,2) DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS `discount_amount` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  ADD COLUMN IF NOT EXISTS `applied_discount` TINYINT(1) NOT NULL DEFAULT 0;

-- Backfill fees from latest fee_discounts snapshot per fee_id (if any exist)
-- This updates original_amount, discount_amount, applied_discount and amount_due to the payable_amount
-- using the most recent applied_at per fee.
UPDATE `fees` f
JOIN (
  SELECT fd1.fee_id, fd1.original_amount, fd1.discount_amount, fd1.payable_amount
  FROM `fee_discounts` fd1
  JOIN (
    SELECT fee_id, MAX(applied_at) AS applied_at
    FROM `fee_discounts`
    GROUP BY fee_id
  ) fd2 ON fd1.fee_id = fd2.fee_id AND fd1.applied_at = fd2.applied_at
) d ON d.fee_id = f.id
SET f.original_amount = COALESCE(f.original_amount, d.original_amount, f.amount_due),
    f.discount_amount = COALESCE(f.discount_amount, d.discount_amount, 0.00),
    f.applied_discount = 1,
    f.amount_due = d.payable_amount;

COMMIT;

-- Diagnostic queries: run these after the migration to inspect current state
-- 1) Do we have any fee_discounts rows?
SELECT COUNT(*) AS fee_discounts_count FROM fee_discounts;

-- 2) Recent discount apply failures recorded by the application
SELECT * FROM bursary_activity WHERE action LIKE 'discount.apply%' ORDER BY id DESC LIMIT 50;

-- 3) Sample inconsistent fees where discount flags are set but fee_discounts missing
SELECT f.id, f.student_id, f.original_amount, f.discount_amount, f.applied_discount, f.amount_due, f.amount_paid, f.balance
FROM fees f
LEFT JOIN fee_discounts d ON d.fee_id = f.id
WHERE f.applied_discount = 1 AND d.fee_id IS NULL
LIMIT 100;

-- 4) Check whether `balance` is a GENERATED column (returns EXTRA column info)
SELECT COLUMN_NAME, EXTRA FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'fees' AND COLUMN_NAME = 'balance';

-- If `balance` is not GENERATED and you want DB-owned balance, convert carefully:
-- (conversion may require dropping the column and re-adding as GENERATED; test on a copy first)

-- Run the following to preview rows where amount_due != original_amount - discount_amount
SELECT id, original_amount, discount_amount, amount_due FROM fees WHERE original_amount IS NOT NULL AND amount_due != COALESCE(original_amount - discount_amount, amount_due) LIMIT 50;

-- End of migration/diagnostic script
