"""Phase 7R.1 firm billing settings

Revision ID: 20260601_phase_7r1_billing_settings
Revises: 20260531_phase_7q3_user_profile
Create Date: 2026-06-01

Adds professional billing settings fields used by GST invoice formatting,
payment tracking and future online payment phases. Idempotent for SQLite dev use.
"""
from __future__ import annotations

from alembic import op
import sqlalchemy as sa

revision = "20260601_phase_7r1_billing_settings"
down_revision = "20260531_phase_7q3_user_profile"
branch_labels = None
depends_on = None


def _columns(table_name: str) -> set[str]:
    bind = op.get_bind()
    inspector = sa.inspect(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 column.name not in _columns(table):
        op.add_column(table, column)


def upgrade() -> None:
    _add_if_missing("billing_settings", sa.Column("pan", sa.String(length=10), nullable=True))
    _add_if_missing("billing_settings", sa.Column("state_code", sa.String(length=2), nullable=True))
    _add_if_missing("billing_settings", sa.Column("contact_email", sa.String(length=255), nullable=True))
    _add_if_missing("billing_settings", sa.Column("contact_mobile", sa.String(length=50), nullable=True))
    _add_if_missing("billing_settings", sa.Column("website_url", sa.String(length=255), nullable=True))
    _add_if_missing("billing_settings", sa.Column("invoice_title", sa.String(length=80), nullable=True))
    _add_if_missing("billing_settings", sa.Column("invoice_number_format", sa.String(length=120), nullable=True))
    _add_if_missing("billing_settings", sa.Column("default_due_days", sa.Integer(), nullable=False, server_default="15"))
    _add_if_missing("billing_settings", sa.Column("default_sac_code", sa.String(length=20), nullable=True))
    _add_if_missing("billing_settings", sa.Column("bank_name", sa.String(length=200), nullable=True))
    _add_if_missing("billing_settings", sa.Column("bank_account_name", sa.String(length=200), nullable=True))
    _add_if_missing("billing_settings", sa.Column("bank_account_number", sa.String(length=50), nullable=True))
    _add_if_missing("billing_settings", sa.Column("bank_ifsc", sa.String(length=20), nullable=True))
    _add_if_missing("billing_settings", sa.Column("upi_id", sa.String(length=100), nullable=True))
    _add_if_missing("billing_settings", sa.Column("authorised_signatory_name", sa.String(length=200), nullable=True))
    _add_if_missing("billing_settings", sa.Column("declaration", sa.Text(), nullable=True))


def downgrade() -> None:
    # No-op downgrade for SQLite/dev safety. Dropping columns in SQLite can require
    # table rebuild and may damage live billing configuration.
    pass
