"""rev_c - branch_id columns on operational tables + grn_items

Revision ID: 0005_rev_c
Revises: 0004_rev_b
Create Date: 2026-09-22
"""
from alembic import op
import sqlalchemy as sa

revision = "0005_rev_c"
down_revision = "0004_rev_b"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.add_column("sales", sa.Column("branch_id", sa.String(length=36), nullable=True))
    op.create_index("ix_sales_branch_id", "sales", ["branch_id"])
    op.add_column("purchase_orders", sa.Column("branch_id", sa.String(length=36), nullable=True))
    op.create_index("ix_purchase_orders_branch_id", "purchase_orders", ["branch_id"])
    op.add_column("grn", sa.Column("branch_id", sa.String(length=36), nullable=True))
    op.create_index("ix_grn_branch_id", "grn", ["branch_id"])
    op.add_column("expenses", sa.Column("branch_id", sa.String(length=36), nullable=True))
    op.create_index("ix_expenses_branch_id", "expenses", ["branch_id"])
    op.add_column("income", sa.Column("branch_id", sa.String(length=36), nullable=True))
    op.create_index("ix_income_branch_id", "income", ["branch_id"])
    op.add_column("payments", sa.Column("branch_id", sa.String(length=36), nullable=True))
    op.create_index("ix_payments_branch_id", "payments", ["branch_id"])

    op.create_table(
        "grn_items",
        sa.Column("id", sa.String(length=36), nullable=False),
        sa.Column("grn_id", sa.String(length=36), nullable=False),
        sa.Column("po_item_id", sa.String(length=36), nullable=True),
        sa.Column("inventory_id", sa.String(length=36), nullable=True),
        sa.Column("description", sa.String(length=200), nullable=False),
        sa.Column("quantity", sa.Integer(), nullable=False),
        sa.Column("unit_price", sa.Float(), nullable=False),
        sa.Column("total", sa.Float(), nullable=False),
        sa.Column("created_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
        sa.ForeignKeyConstraint(["grn_id"], ["grn.id"]),
        sa.ForeignKeyConstraint(["inventory_id"], ["inventory.id"]),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index("ix_grn_items_grn_id", "grn_items", ["grn_id"])


def downgrade() -> None:
    op.drop_index("ix_grn_items_grn_id", table_name="grn_items")
    op.drop_table("grn_items")
    op.drop_index("ix_payments_branch_id", table_name="payments")
    op.drop_column("payments", "branch_id")
    op.drop_index("ix_income_branch_id", table_name="income")
    op.drop_column("income", "branch_id")
    op.drop_index("ix_expenses_branch_id", table_name="expenses")
    op.drop_column("expenses", "branch_id")
    op.drop_index("ix_grn_branch_id", table_name="grn")
    op.drop_column("grn", "branch_id")
    op.drop_index("ix_purchase_orders_branch_id", table_name="purchase_orders")
    op.drop_column("purchase_orders", "branch_id")
    op.drop_index("ix_sales_branch_id", table_name="sales")
    op.drop_column("sales", "branch_id")