"""purchase enhancements

Revision ID: 0d340e128f4e
Revises: 58a5ce7cf557
Create Date: 2026-05-21 11:36:49.240844
"""
from alembic import op
import sqlalchemy as sa


revision = "0d340e128f4e"
down_revision = "58a5ce7cf557"
branch_labels = None
depends_on = None


def upgrade():
    # hsn_master already exists in your DB, so we are not creating it again.

    with op.batch_alter_table("purchase_invoice", schema=None) as batch_op:
        batch_op.add_column(sa.Column("entry_date", sa.Date(), nullable=True))
        batch_op.add_column(sa.Column("posting_date", sa.Date(), nullable=True))
        batch_op.add_column(sa.Column("gst_type", sa.String(length=30), nullable=True))
        batch_op.add_column(sa.Column("is_draft", sa.Boolean(), nullable=True))
        batch_op.add_column(sa.Column("currency_code", sa.String(length=10), nullable=True))
        batch_op.add_column(sa.Column("exchange_rate", sa.Numeric(precision=18, scale=4), nullable=True))
        batch_op.add_column(sa.Column("attachment_path", sa.String(length=255), nullable=True))

    op.execute("""
        UPDATE purchase_invoice
        SET entry_date = bill_date,
            posting_date = bill_date,
            gst_type = 'regular',
            is_draft = 0,
            currency_code = 'INR',
            exchange_rate = 1
        WHERE entry_date IS NULL
           OR posting_date IS NULL
           OR gst_type IS NULL
           OR is_draft IS NULL
           OR currency_code IS NULL
           OR exchange_rate IS NULL
    """)

    op.alter_column(
        "purchase_invoice",
        "entry_date",
        existing_type=sa.Date(),
        nullable=False,
    )

    op.alter_column(
        "purchase_invoice",
        "posting_date",
        existing_type=sa.Date(),
        nullable=False,
    )

    op.alter_column(
        "purchase_invoice",
        "gst_type",
        existing_type=sa.String(length=30),
        nullable=False,
    )

    op.alter_column(
        "purchase_invoice",
        "is_draft",
        existing_type=sa.Boolean(),
        nullable=False,
    )

    with op.batch_alter_table("purchase_invoice_item", schema=None) as batch_op:
        batch_op.add_column(sa.Column("gst_type", sa.String(length=30), nullable=True))

    op.execute("""
        UPDATE purchase_invoice_item
        SET gst_type = 'regular'
        WHERE gst_type IS NULL
    """)


def downgrade():
    with op.batch_alter_table("purchase_invoice_item", schema=None) as batch_op:
        batch_op.drop_column("gst_type")

    with op.batch_alter_table("purchase_invoice", schema=None) as batch_op:
        batch_op.drop_column("attachment_path")
        batch_op.drop_column("exchange_rate")
        batch_op.drop_column("currency_code")
        batch_op.drop_column("is_draft")
        batch_op.drop_column("gst_type")
        batch_op.drop_column("posting_date")
        batch_op.drop_column("entry_date")

    # Do not drop hsn_master because it already existed/was created separately.