"""Add invoice numbering fields

Revision ID: 5a4d09d23119
Revises: f66732ff5915
Create Date: 2025-05-27 16:36:06.295404

"""

import sqlalchemy as sa
from alembic import op

# Polar Custom Imports

# revision identifiers, used by Alembic.
revision = "5a4d09d23119"
down_revision = "f66732ff5915"
branch_labels: tuple[str] | None = None
depends_on: tuple[str] | None = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column("orders", sa.Column("invoice_number", sa.String(), nullable=True))
    op.add_column("orders", sa.Column("invoice_path", sa.String(), nullable=True))
    op.create_unique_constraint(
        op.f("orders_invoice_number_key"), "orders", ["invoice_number"]
    )
    op.add_column(
        "organizations",
        sa.Column("customer_invoice_prefix", sa.String(), nullable=True),
    )
    op.add_column(
        "organizations",
        sa.Column("customer_invoice_next_number", sa.Integer(), nullable=True),
    )

    op.execute(
        """
        UPDATE organizations
        SET customer_invoice_prefix = UPPER(slug),
            customer_invoice_next_number = 1;
        """
    )

    op.alter_column(
        "organizations",
        "customer_invoice_prefix",
        existing_type=sa.String(),
        nullable=False,
    )
    op.alter_column(
        "organizations",
        "customer_invoice_next_number",
        existing_type=sa.Integer(),
        nullable=False,
        server_default="1",
    )

    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("organizations", "customer_invoice_next_number")
    op.drop_column("organizations", "customer_invoice_prefix")
    op.drop_constraint(op.f("orders_invoice_number_key"), "orders", type_="unique")
    op.drop_column("orders", "invoice_path")
    op.drop_column("orders", "invoice_number")
    # ### end Alembic commands ###
