"""Phase 7R.6A Cashfree payment gateway integration

Revision ID: 20260607_phase_7r6a_cashfree
Revises: 20260606_phase_7r6_payumoney
Create Date: 2026-06-07

Adds Cashfree gateway settings and generic Cashfree fields to the existing online
payment transaction ledger. Defensive for SQLite development databases.
"""
from __future__ import annotations

from alembic import op
import sqlalchemy as sa

revision = "20260607_phase_7r6a_cashfree"
down_revision = "20260606_phase_7r6_payumoney"
branch_labels = None
depends_on = None


def _tables() -> set[str]:
    return set(sa.inspect(op.get_bind()).get_table_names())


def _columns(table_name: str) -> set[str]:
    inspector = sa.inspect(op.get_bind())
    if table_name not in inspector.get_table_names():
        return set()
    return {c["name"] for c in inspector.get_columns(table_name)}


def _add_if_missing(table: str, column: sa.Column) -> None:
    if table in _tables() and column.name not in _columns(table):
        op.add_column(table, column)


def _index_exists(index_name: str) -> bool:
    inspector = sa.inspect(op.get_bind())
    for table_name in inspector.get_table_names():
        for idx in inspector.get_indexes(table_name):
            if idx.get("name") == index_name:
                return True
    return False


def _create_index_if_missing(name: str, table: str, columns: list[str], unique: bool = False) -> None:
    if table in _tables() and not _index_exists(name):
        op.create_index(name, table, columns, unique=unique)


def upgrade() -> None:
    _add_if_missing("billing_settings", sa.Column("cashfree_enabled", sa.Boolean(), nullable=False, server_default=sa.false()))
    _add_if_missing("billing_settings", sa.Column("cashfree_mode", sa.String(length=20), nullable=False, server_default="TEST"))
    _add_if_missing("billing_settings", sa.Column("cashfree_client_id", sa.String(length=180), nullable=True))
    _add_if_missing("billing_settings", sa.Column("cashfree_client_secret", sa.String(length=240), nullable=True))
    _add_if_missing("billing_settings", sa.Column("cashfree_api_version", sa.String(length=20), nullable=False, server_default="2023-08-01"))
    _add_if_missing("billing_settings", sa.Column("cashfree_order_note", sa.String(length=250), nullable=True))

    _add_if_missing("billing_online_payment_transactions", sa.Column("cashfree_order_id", sa.String(length=120), nullable=True))
    _add_if_missing("billing_online_payment_transactions", sa.Column("cashfree_cf_order_id", sa.String(length=120), nullable=True))
    _add_if_missing("billing_online_payment_transactions", sa.Column("cashfree_payment_session_id", sa.String(length=500), nullable=True))
    _add_if_missing("billing_online_payment_transactions", sa.Column("cashfree_payment_id", sa.String(length=120), nullable=True))
    _add_if_missing("billing_online_payment_transactions", sa.Column("webhook_event_id", sa.String(length=120), nullable=True))

    _create_index_if_missing("ix_billing_online_payment_transactions_cashfree_order_id", "billing_online_payment_transactions", ["cashfree_order_id"])
    _create_index_if_missing("ix_billing_online_payment_transactions_cashfree_cf_order_id", "billing_online_payment_transactions", ["cashfree_cf_order_id"])
    _create_index_if_missing("ix_billing_online_payment_transactions_cashfree_payment_id", "billing_online_payment_transactions", ["cashfree_payment_id"])
    _create_index_if_missing("ix_billing_online_payment_transactions_webhook_event_id", "billing_online_payment_transactions", ["webhook_event_id"])


def downgrade() -> None:
    # SQLite cannot safely drop columns in older versions. Keep columns to avoid data loss.
    pass
