<?php
declare(strict_types=1);

return function (\App\Core\Database $db): void {
    $table = 'divorce_cases';

    $columnsToAdd = [
        'divorce_certificate_path' => "VARCHAR(500) NULL AFTER `divorce_date`",
        'spouse_qualification_id'  => "BIGINT UNSIGNED NULL AFTER `divorce_certificate_path`",
        'board_decision_number'    => "VARCHAR(50) NULL AFTER `fee_amount`",
        'board_decision_date'      => "DATE NULL AFTER `board_decision_number`",
        'board_notes'              => "TEXT NULL AFTER `board_decision_date`",
        'annual_subscription_fee'  => "DECIMAL(15,2) NULL DEFAULT 0 AFTER `fee_amount`",
        'form_fee'                 => "DECIMAL(15,2) NULL DEFAULT 0 AFTER `annual_subscription_fee`",
        'total_fee'                => "DECIMAL(15,2) NULL DEFAULT 0 AFTER `form_fee`",
        'original_member_id'       => "BIGINT UNSIGNED NULL AFTER `spouse_new_membership_number`",
        'original_membership_number' => "VARCHAR(20) NULL AFTER `original_member_id`",
    ];

    foreach ($columnsToAdd as $col => $definition) {
        $exists = $db->selectOne(
            "SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?",
            [$table, $col]
        );
        if (!$exists) {
            $db->raw("ALTER TABLE `{$table}` ADD COLUMN `{$col}` {$definition}");
        }
    }

    // Add transferred_from_divorce_id to members table for linking back
    $exists = $db->selectOne(
        "SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'members' AND column_name = 'transferred_from_divorce_id'",
        []
    );
    if (!$exists) {
        $db->raw("ALTER TABLE `members` ADD COLUMN `transferred_from_divorce_id` BIGINT UNSIGNED NULL");
    }

    $exists = $db->selectOne(
        "SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'members' AND column_name = 'original_membership_number'",
        []
    );
    if (!$exists) {
        $db->raw("ALTER TABLE `members` ADD COLUMN `original_membership_number` VARCHAR(20) NULL");
    }
};
