"""invoice negotiation override

Revision ID: 27bc1bfc33dc
Revises: 632878c8f243
Create Date: 2026-05-13 18:23:54.436874

Adds mps_invoice.negotiation_override_in_cents (nullable BigInteger).
When set, Invoice.total_in_cents short-circuits to this override +
handling, bypassing the subtotal/discount math.

Why: carts linked to an accepted offer or winning auction have a
negotiated total that overrides the sum of line items. The cart UI
honored this, but Invoice.total_in_cents summed line items only — so
every payment method (Stripe, PayPal, Monero, Dogecoin) was charging
the list price for negotiated carts. This column lets the invoice
inherit the cart's override at construction time.
"""
from alembic import op
import sqlalchemy as sa


revision = '27bc1bfc33dc'
down_revision = '632878c8f243'
branch_labels = None
depends_on = None


def _column_exists(table, column):
    conn = op.get_bind()
    result = conn.execute(sa.text(f"PRAGMA table_info({table})"))
    return any(row[1] == column for row in result.fetchall())


def upgrade():
    if not _column_exists("mps_invoice", "negotiation_override_in_cents"):
        op.add_column(
            "mps_invoice",
            sa.Column(
                "negotiation_override_in_cents",
                sa.BigInteger(),
                nullable=True,
            ),
        )


def downgrade():
    if _column_exists("mps_invoice", "negotiation_override_in_cents"):
        op.drop_column("mps_invoice", "negotiation_override_in_cents")
