"""Remove payment_id circular references

Revision ID: ff416380db04
Revises: c8dc03c2cf76
Create Date: 2025-01-02 01:53:52.140515

"""

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision: str = "ff416380db04"
down_revision: str | None = "c8dc03c2cf76"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column("paymentmethods", sa.Column("is_used", sa.Boolean(), nullable=True))
    op.execute("""
        UPDATE paymentmethods
        SET is_used = true
        FROM invoices
        WHERE invoices.payment_id = paymentmethods.id
    """)
    op.drop_constraint("invoices_payment_id_paymentmethods_fkey", "invoices", type_="foreignkey")
    op.drop_column("invoices", "payment_id")
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column("invoices", sa.Column("payment_id", sa.TEXT(), autoincrement=False, nullable=True))
    op.create_foreign_key(
        "invoices_payment_id_paymentmethods_fkey", "invoices", "paymentmethods", ["payment_id"], ["id"], ondelete="SET NULL"
    )
    op.execute("""
        UPDATE invoices
        SET payment_id = paymentmethods.id
        FROM paymentmethods
        WHERE paymentmethods.invoice_id = invoices.id
        AND paymentmethods.is_used = true
    """)
    op.drop_column("paymentmethods", "is_used")
    # ### end Alembic commands ###
