-- ============================================================================
-- MIKHMON PREMIUM — PRODUCTION DEPLOYMENT CONSOLIDATED MIGRATION
-- Sprints 03–09: Multi-Router Isolation, Package Pricing, Customer Directory,
-- Invoicing Cycles, Rolling 30-Day Subscriptions & Reactivation Journal
--
-- COMPATIBILITY: MySQL 5.7+, MySQL 8.0+, MariaDB 10.3+
-- IDEMPOTENCY: Safe to run repeatedly; uses conditional metadata inspection
-- ============================================================================

DELIMITER $$

-- Procedure to safely add a column if not already present
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$$

-- Procedure to safely add an index if not already present
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$$

DELIMITER ;

-- ----------------------------------------------------------------------------
-- 1. BILLING PROFILES ENHANCEMENTS
-- ----------------------------------------------------------------------------
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`");

CALL add_index_if_not_exists('billing_profiles', 'idx_router_commercial_status', "(`router_id`, `commercial_status`)");

-- ----------------------------------------------------------------------------
-- 2. BILLING CUSTOMERS ENHANCEMENTS (ROLLING 30-DAY SUBSCRIPTION MODEL)
-- ----------------------------------------------------------------------------
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. BILLING INVOICES ENHANCEMENTS
-- ----------------------------------------------------------------------------
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`");

-- Expand status enum to include partially_paid
ALTER TABLE `billing_invoices`
  MODIFY COLUMN `status` ENUM('draft','unpaid','partially_paid','paid','overdue','cancelled') NOT NULL DEFAULT 'unpaid';

-- Widen period from CHAR(7) to VARCHAR(32) for rolling sub-month cycles
ALTER TABLE `billing_invoices`
  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`)");

-- ----------------------------------------------------------------------------
-- 4. BILLING PAYMENTS ENHANCEMENTS
-- ----------------------------------------------------------------------------
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. BILLING REACTIVATIONS TABLE (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;

-- Clean up helper procedures
DROP PROCEDURE IF EXISTS `add_column_if_not_exists`;
DROP PROCEDURE IF EXISTS `add_index_if_not_exists`;

