"""Fix stale order_lines.item_status: auto-approve lines for non-draft orders

Revision ID: 017
Revises: 016
Create Date: 2026-03-02

"""
from typing import Sequence, Union
from alembic import op

revision: str = "017"
down_revision: Union[str, None] = "016"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Order lines belonging to submitted/processing/completed orders should
    # be "approved", not stuck at "pending".  The new Product Library workflow
    # has no per-item approval step — submission implies approval.
    op.execute("""
        UPDATE order_lines
        SET item_status = 'approved'
        WHERE item_status = 'pending'
          AND order_id IN (
              SELECT id FROM orders
              WHERE status IN ('submitted', 'processing', 'completed')
          )
    """)

    # Lines belonging to rejected orders should be "rejected".
    op.execute("""
        UPDATE order_lines
        SET item_status = 'rejected'
        WHERE item_status = 'pending'
          AND order_id IN (
              SELECT id FROM orders WHERE status = 'rejected'
          )
    """)


def downgrade() -> None:
    # Cannot reliably revert — the original values were all "pending" anyway.
    pass
