-- ============================================================================
-- MIKHMON PREMIUM — SPRINT 10 CONSOLIDATED RELEASE MIGRATION
-- Target File: database/deploy_billing_consolidated_release.sql
--
-- Consolidates Sprints 03–09:
-- 1. Multi-Router Isolation & Stable Router Identity Baseline (Sprint 03)
-- 2. PPPoE Package Pricing & PPP Profile Bindings (Sprint 04)
-- 3. Customer Directory & Multi-Router PPP Secret Linkage (Sprint 05)
-- 4. Monthly Invoicing Cycles, Outstanding Balances & Partial Invoicing (Sprint 06)
-- 5. Payment Management, Partial Payments, Reconciliation & Reporting (Sprint 07)
-- 6. Rolling 30-Day Subscription Lifecycle & Service Separation (Sprint 09)
-- 7. Two-Phase Idempotent Reactivation Operation Journal (Sprint 09)
--
-- PROPERTIES:
-- - 100% Idempotent (safe to run repeatedly, on fresh or partially migrated schemas)
-- - Zero Data Deletion / Loss (additive modifications and non-destructive widenings)
-- - Safe Constraint Handling (conditional index addition and drop)
-- - Compatible with MySQL 5.7+, MySQL 8.0+, MariaDB 10.3+
--
-- NOTICE: DO NOT EXECUTE DIRECTLY ON PRODUCTION WITHOUT AUTHORIZATION.
-- ============================================================================

DELIMITER $$

-- ----------------------------------------------------------------------------
-- HELPER STORED PROCEDURE 1: add_column_if_not_exists
-- ----------------------------------------------------------------------------
DROP PROCEDURE IF EXISTS `add_column_if_not_exists`$$
CREATE PROCEDURE `add_column_if_not_exists`(
    IN tableName VARCHAR(64),
    IN columnName VARCHAR(64),
    IN columnDefinition TEXT
)
BEGIN
    DECLARE colCount INT;
    SELECT COUNT(*) INTO colCount 
    FROM information_schema.COLUMNS 
    WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = tableName 
      AND COLUMN_NAME = columnName;
      
    IF colCount = 0 THEN
        SET @sql = CONCAT('ALTER TABLE `', tableName, '` ADD COLUMN `', columnName, '` ', columnDefinition);
        PREPARE stmt FROM @sql;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END IF;
END$$

-- ----------------------------------------------------------------------------
-- HELPER STORED PROCEDURE 2: add_index_if_not_exists
-- ----------------------------------------------------------------------------
DROP PROCEDURE IF EXISTS `add_index_if_not_exists`$$
CREATE PROCEDURE `add_index_if_not_exists`(
    IN tableName VARCHAR(64),
    IN indexName VARCHAR(64),
    IN indexDefinition TEXT
)
BEGIN
    DECLARE idxCount INT;
    SELECT COUNT(*) INTO idxCount 
    FROM information_schema.STATISTICS 
    WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = tableName 
      AND INDEX_NAME = indexName;
      
    IF idxCount = 0 THEN
        SET @sql = CONCAT('ALTER TABLE `', tableName, '` ADD INDEX `', indexName, '` ', indexDefinition);
        PREPARE stmt FROM @sql;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END IF;
END$$

-- ----------------------------------------------------------------------------
-- HELPER STORED PROCEDURE 3: add_unique_if_not_exists
-- ----------------------------------------------------------------------------
DROP PROCEDURE IF EXISTS `add_unique_if_not_exists`$$
CREATE PROCEDURE `add_unique_if_not_exists`(
    IN tableName VARCHAR(64),
    IN indexName VARCHAR(64),
    IN indexDefinition TEXT
)
BEGIN
    DECLARE idxCount INT;
    SELECT COUNT(*) INTO idxCount 
    FROM information_schema.STATISTICS 
    WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = tableName 
      AND INDEX_NAME = indexName;
      
    IF idxCount = 0 THEN
        SET @sql = CONCAT('ALTER TABLE `', tableName, '` ADD UNIQUE KEY `', indexName, '` ', indexDefinition);
        PREPARE stmt FROM @sql;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END IF;
END$$

-- ----------------------------------------------------------------------------
-- HELPER STORED PROCEDURE 4: drop_index_if_exists
-- ----------------------------------------------------------------------------
DROP PROCEDURE IF EXISTS `drop_index_if_exists`$$
CREATE PROCEDURE `drop_index_if_exists`(
    IN tableName VARCHAR(64),
    IN indexName VARCHAR(64)
)
BEGIN
    DECLARE idxCount INT;
    SELECT COUNT(*) INTO idxCount 
    FROM information_schema.STATISTICS 
    WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = tableName 
      AND INDEX_NAME = indexName;
      
    IF idxCount > 0 THEN
        SET @sql = CONCAT('ALTER TABLE `', tableName, '` DROP INDEX `', indexName, '`');
        PREPARE stmt FROM @sql;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END IF;
END$$

DELIMITER ;

-- ============================================================================
-- 1. TABLE: billing_profiles (Package Pricing & Router Bindings)
-- ============================================================================
CALL add_column_if_not_exists('billing_profiles', 'router_id', "VARCHAR(64) NOT NULL DEFAULT 'default' AFTER `id`");
CALL add_column_if_not_exists('billing_profiles', 'router_session', "VARCHAR(50) NOT NULL DEFAULT 'default' AFTER `router_id`");
CALL add_column_if_not_exists('billing_profiles', 'commercial_status', "ENUM('active','inactive') NOT NULL DEFAULT 'active' AFTER `price_monthly`");
CALL add_column_if_not_exists('billing_profiles', 'currency', "VARCHAR(10) NOT NULL DEFAULT 'IDR' AFTER `commercial_status`");

-- Replace legacy global unique index with router-scoped unique index
CALL drop_index_if_exists('billing_profiles', 'uniq_profile_name');
CALL add_unique_if_not_exists('billing_profiles', 'uniq_router_profile', "(`router_id`, `profile_name`)");
CALL add_index_if_not_exists('billing_profiles', 'idx_router_commercial_status', "(`router_id`, `commercial_status`)");

-- ============================================================================
-- 2. TABLE: billing_customers (Directory, Scoping & Rolling 30-Day Subscriptions)
-- ============================================================================
CALL add_column_if_not_exists('billing_customers', 'router_id', "VARCHAR(64) NOT NULL DEFAULT 'default' AFTER `profile_id`");
CALL add_column_if_not_exists('billing_customers', 'router_session', "VARCHAR(50) NOT NULL DEFAULT 'default' AFTER `router_id`");
CALL add_column_if_not_exists('billing_customers', 'pppoe_username', "VARCHAR(100) DEFAULT NULL AFTER `service_number`");
CALL add_column_if_not_exists('billing_customers', 'current_service_status', "ENUM('active', 'isolated', 'awaiting_reactivation', 'expired') NOT NULL DEFAULT 'active' AFTER `status`");
CALL add_column_if_not_exists('billing_customers', 'last_verified_payment_at', "DATETIME NULL AFTER `current_service_status`");
CALL add_column_if_not_exists('billing_customers', 'activated_at', "DATETIME NULL AFTER `last_verified_payment_at`");
CALL add_column_if_not_exists('billing_customers', 'expires_at', "DATETIME NULL AFTER `activated_at`");
CALL add_column_if_not_exists('billing_customers', 'renewal_source_invoice_id', "INT UNSIGNED NULL AFTER `expires_at`");
CALL add_column_if_not_exists('billing_customers', 'reactivation_status', "ENUM('none', 'pending_confirmation', 'reactivation_pending', 'reactivated', 'reactivation_failed', 'needs_manual_review') NOT NULL DEFAULT 'none' AFTER `renewal_source_invoice_id`");
CALL add_column_if_not_exists('billing_customers', 'last_router_sync_at', "DATETIME NULL AFTER `reactivation_status`");

CALL add_index_if_not_exists('billing_customers', 'idx_router_customer_pppoe', "(`router_id`, `pppoe_username`)");
CALL add_index_if_not_exists('billing_customers', 'idx_router_customer_status', "(`router_id`, `status`)");
CALL add_index_if_not_exists('billing_customers', 'idx_router_customer_profile', "(`router_id`, `profile_id`)");
CALL add_index_if_not_exists('billing_customers', 'idx_customer_expires_at', "(`expires_at`)");
CALL add_index_if_not_exists('billing_customers', 'idx_customer_service_status', "(`current_service_status`)");
CALL add_index_if_not_exists('billing_customers', 'idx_customer_reactivation_status', "(`reactivation_status`)");

-- ============================================================================
-- 3. TABLE: billing_invoices (Cycles, Partial Payments & Rolling 30-Day Period)
-- ============================================================================
CALL add_column_if_not_exists('billing_invoices', 'router_id', "VARCHAR(64) NOT NULL DEFAULT 'default' AFTER `customer_id`");
CALL add_column_if_not_exists('billing_invoices', 'router_session', "VARCHAR(50) NOT NULL DEFAULT 'default' AFTER `router_id`");
CALL add_column_if_not_exists('billing_invoices', 'paid_amount', "DECIMAL(12,2) NOT NULL DEFAULT 0.00 AFTER `amount`");
CALL add_column_if_not_exists('billing_invoices', 'outstanding_amount', "DECIMAL(12,2) NOT NULL DEFAULT 0.00 AFTER `paid_amount`");

-- Non-destructive column definition updates
ALTER TABLE `billing_invoices`
  MODIFY COLUMN `status` ENUM('draft','unpaid','partially_paid','paid','overdue','cancelled') NOT NULL DEFAULT 'unpaid',
  MODIFY COLUMN `period` VARCHAR(32) NOT NULL;

CALL add_index_if_not_exists('billing_invoices', 'idx_router_period', "(`router_id`, `period`)");
CALL add_index_if_not_exists('billing_invoices', 'idx_status_due', "(`status`, `due_date`)");
CALL add_index_if_not_exists('billing_invoices', 'idx_reference_number', "(`reference_number`)");

-- Safe backfill for any pre-existing invoices before partial-payment columns existed
UPDATE `billing_invoices`
SET `outstanding_amount` = GREATEST(0.00, `amount` - `paid_amount`)
WHERE `status` IN ('unpaid', 'partially_paid', 'overdue')
  AND `outstanding_amount` = 0.00
  AND (`amount` - `paid_amount`) > 0.00;

UPDATE `billing_invoices`
SET `paid_amount` = `amount`, `outstanding_amount` = 0.00
WHERE `status` = 'paid'
  AND `paid_amount` = 0.00
  AND `amount` > 0.00;

-- ============================================================================
-- 4. TABLE: billing_payments (Multi-Router Payments, Void Auditing & References)
-- ============================================================================
CALL add_column_if_not_exists('billing_payments', 'customer_id', "INT UNSIGNED DEFAULT NULL AFTER `invoice_id`");
CALL add_column_if_not_exists('billing_payments', 'router_id', "VARCHAR(64) NOT NULL DEFAULT 'default' AFTER `customer_id`");
CALL add_column_if_not_exists('billing_payments', 'router_session', "VARCHAR(50) NOT NULL DEFAULT 'default' AFTER `router_id`");
CALL add_column_if_not_exists('billing_payments', 'reference_number', "VARCHAR(100) DEFAULT NULL AFTER `method`");
CALL add_column_if_not_exists('billing_payments', 'is_voided', "TINYINT(1) NOT NULL DEFAULT 0 AFTER `notes`");
CALL add_column_if_not_exists('billing_payments', 'voided_at', "DATETIME DEFAULT NULL AFTER `is_voided`");
CALL add_column_if_not_exists('billing_payments', 'voided_by', "INT UNSIGNED DEFAULT NULL AFTER `voided_at`");
CALL add_column_if_not_exists('billing_payments', 'void_reason', "VARCHAR(255) DEFAULT NULL AFTER `voided_by`");

CALL add_index_if_not_exists('billing_payments', 'idx_payment_date', "(`payment_date`)");
CALL add_index_if_not_exists('billing_payments', 'idx_router_payment_date', "(`router_id`, `payment_date`)");
CALL add_index_if_not_exists('billing_payments', 'idx_customer_payment', "(`customer_id`, `payment_date`)");
CALL add_index_if_not_exists('billing_payments', 'idx_payment_reference', "(`reference_number`)");
CALL add_index_if_not_exists('billing_payments', 'idx_payment_void', "(`is_voided`)");

-- ============================================================================
-- 5. TABLE: billing_settings (Multi-Router Setting Scoping)
-- ============================================================================
CALL add_column_if_not_exists('billing_settings', 'router_id', "VARCHAR(64) NOT NULL DEFAULT 'global' AFTER `setting_key`");
CALL add_index_if_not_exists('billing_settings', 'idx_setting_router', "(`router_id`, `setting_key`)");

-- ============================================================================
-- 6. TABLE: billing_reactivations (Two-Phase Idempotent Operation Journal)
-- ============================================================================
CREATE TABLE IF NOT EXISTS `billing_reactivations` (
    `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    `idempotency_token` VARCHAR(64) NOT NULL UNIQUE,
    `customer_id` INT UNSIGNED NOT NULL,
    `invoice_id` INT UNSIGNED NULL,
    `router_id` VARCHAR(64) NOT NULL DEFAULT 'default',
    `router_session` VARCHAR(64) NOT NULL DEFAULT 'default',
    `username` VARCHAR(64) NOT NULL,
    `target_profile` VARCHAR(64) NOT NULL,
    `previous_profile` VARCHAR(64) NOT NULL,
    `expiration_policy` ENUM('calendar_cycle', 'rolling_30d', 'prorated') NOT NULL DEFAULT 'rolling_30d',
    `status` ENUM('pending', 'profile_updated', 'session_dropped', 'scheduler_synced', 'completed', 'failed', 'rolled_back') NOT NULL DEFAULT 'pending',
    `step_journal` LONGTEXT NULL,
    `partial_failure_step` VARCHAR(64) NULL,
    `error_message` TEXT NULL,
    `retry_count` INT UNSIGNED NOT NULL DEFAULT 0,
    `created_by` VARCHAR(64) NULL,
    `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    `completed_at` DATETIME NULL,
    INDEX `idx_reactivation_customer` (`customer_id`),
    INDEX `idx_reactivation_invoice` (`invoice_id`),
    INDEX `idx_reactivation_status` (`status`),
    INDEX `idx_reactivation_router` (`router_id`, `router_session`),
    INDEX `idx_reactivation_username` (`username`),
    INDEX `idx_reactivation_created` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ============================================================================
-- CLEANUP HELPER STORED PROCEDURES
-- ============================================================================
DROP PROCEDURE IF EXISTS `add_column_if_not_exists`;
DROP PROCEDURE IF EXISTS `add_index_if_not_exists`;
DROP PROCEDURE IF EXISTS `add_unique_if_not_exists`;
DROP PROCEDURE IF EXISTS `drop_index_if_exists`;

