"""Phase 7R.2 GST invoice format

Revision ID: 20260602_phase_7r2_gst_invoice
Revises: 20260601_phase_7r1_billing_settings
Create Date: 2026-06-02

Adds GST invoice snapshot fields, place of supply, reverse charge,
SAC code per line and amount-in-words support. The migration is
idempotent for the existing SQLite development workflow.
"""
from __future__ import annotations

from alembic import op
import sqlalchemy as sa

revision = "20260602_phase_7r2_gst_invoice"
down_revision = "20260601_phase_7r1_billing_settings"
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_invoices", sa.Column("invoice_title", sa.String(length=80), nullable=True))
    _add_if_missing("billing_invoices", sa.Column("place_of_supply", sa.String(length=120), nullable=True))
    _add_if_missing("billing_invoices", sa.Column("reverse_charge", sa.Boolean(), nullable=False, server_default=sa.false()))
    _add_if_missing("billing_invoices", sa.Column("client_legal_name", sa.String(length=200), nullable=True))
    _add_if_missing("billing_invoices", sa.Column("client_trade_name", sa.String(length=200), nullable=True))
    _add_if_missing("billing_invoices", sa.Column("client_gstin", sa.String(length=20), nullable=True))
    _add_if_missing("billing_invoices", sa.Column("client_pan", sa.String(length=20), nullable=True))
    _add_if_missing("billing_invoices", sa.Column("client_billing_address", sa.Text(), nullable=True))
    _add_if_missing("billing_invoices", sa.Column("client_state", sa.String(length=100), nullable=True))
    _add_if_missing("billing_invoices", sa.Column("client_state_code", sa.String(length=2), nullable=True))
    _add_if_missing("billing_invoices", sa.Column("client_email", sa.String(length=255), nullable=True))
    _add_if_missing("billing_invoices", sa.Column("client_mobile", sa.String(length=50), nullable=True))
    _add_if_missing("billing_invoices", sa.Column("amount_in_words", sa.String(length=500), nullable=True))
    _add_if_missing("billing_invoice_lines", sa.Column("sac_code", sa.String(length=20), nullable=True))


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