"""Create Payout

Revision ID: 3599a43930ce
Revises: a314082ec20e
Create Date: 2025-06-02 16:29:00.879382

"""

import sqlalchemy as sa
from alembic import op

# Polar Custom Imports

# revision identifiers, used by Alembic.
revision = "3599a43930ce"
down_revision = "a314082ec20e"
branch_labels: tuple[str] | None = None
depends_on: tuple[str] | None = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "payouts",
        sa.Column("id", sa.Uuid(), nullable=False),
        sa.Column("created_at", sa.TIMESTAMP(timezone=True), nullable=False),
        sa.Column("modified_at", sa.TIMESTAMP(timezone=True), nullable=True),
        sa.Column("deleted_at", sa.TIMESTAMP(timezone=True), nullable=True),
        sa.Column(
            "processor",
            sa.String(),
            nullable=False,
        ),
        sa.Column("processor_id", sa.String(), nullable=True),
        sa.Column("status", sa.String(), nullable=False),
        sa.Column("currency", sa.String(length=3), nullable=False),
        sa.Column("amount", sa.BigInteger(), nullable=False),
        sa.Column("fees_amount", sa.BigInteger(), nullable=False),
        sa.Column("account_currency", sa.String(length=3), nullable=False),
        sa.Column("account_amount", sa.BigInteger(), nullable=False),
        sa.Column("account_id", sa.Uuid(), nullable=False),
        sa.Column("invoice_number", sa.String(), nullable=True),
        sa.Column("invoice_notes", sa.Text(), nullable=True),
        sa.Column("invoice_path", sa.String(), nullable=True),
        sa.ForeignKeyConstraint(
            ["account_id"],
            ["accounts.id"],
            name=op.f("payouts_account_id_fkey"),
            ondelete="restrict",
        ),
        sa.PrimaryKeyConstraint("id", name=op.f("payouts_pkey")),
    )
    op.create_index(
        op.f("ix_payouts_account_id"), "payouts", ["account_id"], unique=False
    )
    op.create_index(
        op.f("ix_payouts_created_at"), "payouts", ["created_at"], unique=False
    )
    op.create_index(
        op.f("ix_payouts_deleted_at"), "payouts", ["deleted_at"], unique=False
    )
    op.create_index(
        op.f("ix_payouts_modified_at"), "payouts", ["modified_at"], unique=False
    )
    op.create_index(
        op.f("ix_payouts_processor_id"), "payouts", ["processor_id"], unique=False
    )
    op.create_index(op.f("ix_payouts_status"), "payouts", ["status"], unique=False)

    op.add_column(
        "payouts",
        sa.Column(
            "tmp_transaction_id",
            sa.Uuid(),
            nullable=False,
        ),
    )

    op.execute(
        """
        INSERT INTO payouts (
            tmp_transaction_id,
            id,
            created_at,
            modified_at,
            processor,
            processor_id,
            status,
            currency,
            amount,
            fees_amount,
            account_currency,
            account_amount,
            account_id
        )
        SELECT
            id,
            uuid_generate_v4(),
            created_at,
            modified_at,
            processor,
            payout_id,
            CASE
                WHEN payout_id IS NULL THEN 'pending'
                ELSE 'succeeded'
            END,
            currency,
            -amount,
            0,
            account_currency,
            -account_amount,
            account_id
        FROM transactions
        WHERE type = 'payout'
        """
    )

    op.execute(
        """
        UPDATE payouts
        SET fees_amount = (
            SELECT COALESCE(SUM(amount), 0)
            FROM transactions
            WHERE transactions.incurred_by_transaction_id = payouts.tmp_transaction_id
            AND transactions.account_id IS NULL
        )
        """
    )

    op.add_column(
        "transactions",
        sa.Column(
            "tmp_payout_id",
            sa.Uuid(),
            nullable=True,
        ),
    )

    op.execute(
        """
        UPDATE transactions
        SET tmp_payout_id = (
            SELECT id
            FROM payouts
            WHERE payouts.tmp_transaction_id = transactions.id
        )
        WHERE type = 'payout'
        """
    )

    op.drop_column("transactions", "payout_id")
    op.alter_column(
        "transactions",
        "tmp_payout_id",
        existing_type=sa.Uuid(),
        new_column_name="payout_id",
    )
    op.create_foreign_key(
        op.f("transactions_payout_id_fkey"),
        "transactions",
        "payouts",
        ["payout_id"],
        ["id"],
    )
    op.drop_column("payouts", "tmp_transaction_id")

    op.alter_column(
        "accounts", "currency", existing_type=sa.VARCHAR(length=3), nullable=False
    )
    op.create_index(
        op.f("ix_transactions_payout_id"), "transactions", ["payout_id"], unique=False
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(
        op.f("transactions_payout_id_fkey"), "transactions", type_="foreignkey"
    )

    op.add_column(
        "transactions",
        sa.Column(
            "tmp_payout_id",
            sa.VARCHAR(),
            nullable=True,
        ),
    )
    op.execute(
        """
        UPDATE transactions
        SET tmp_payout_id = (
            SELECT processor_id
            FROM payouts
            WHERE payouts.id = transactions.payout_id
        )
        WHERE type = 'payout'
        """
    )
    op.drop_column("transactions", "payout_id")
    op.alter_column(
        "transactions",
        "tmp_payout_id",
        existing_type=sa.VARCHAR(),
        new_column_name="payout_id",
    )

    op.drop_index(op.f("ix_payouts_status"), table_name="payouts")
    op.drop_index(op.f("ix_payouts_processor_id"), table_name="payouts")
    op.drop_index(op.f("ix_payouts_modified_at"), table_name="payouts")
    op.drop_index(op.f("ix_payouts_deleted_at"), table_name="payouts")
    op.drop_index(op.f("ix_payouts_created_at"), table_name="payouts")
    op.drop_index(op.f("ix_payouts_account_id"), table_name="payouts")
    op.drop_table("payouts")
    # ### end Alembic commands ###
