"""Remove legacy pickup_slot_id column from sale_order.

This migration drops the unused pickup_slot_id column which used to store a
snapshot of the assigned slot on each sale.order. We no longer persist that
reference; keep a human readable `pickup_slot_label` instead.
"""

import logging

_logger = logging.getLogger(__name__)


def migrate(cr, version):
    # Raw SQL is used to ensure the column is dropped even if foreign key
    # constraints exist. We try to drop the FK constraint first and then the
    # column. Use IF EXISTS to avoid errors on already-migrated DBs.
    try:
        # Try dropping common FK constraint name (Postgres naming)
        cr.execute("""
            DO $$
            BEGIN
                IF EXISTS (
                    SELECT 1
                    FROM pg_constraint
                    WHERE conrelid = 'sale_order'::regclass
                      AND conname = 'sale_order_pickup_slot_id_fkey'
                ) THEN
                    ALTER TABLE sale_order DROP CONSTRAINT sale_order_pickup_slot_id_fkey;
                END IF;
            END$$;
            """)
    except Exception as exc:  # pragma: no cover - DB-level migration safeguard
        # Not critical; constraint may have different name or not exist
        _logger.debug(
            "Could not drop FK constraint for sale_order.pickup_slot_id: %s", exc
        )

    try:
        cr.execute("ALTER TABLE sale_order DROP COLUMN IF EXISTS pickup_slot_id;")
    except Exception as exc:  # pragma: no cover - DB-level migration safeguard
        # If the column cannot be dropped (e.g. referenced elsewhere), log and
        # continue; DB admins can drop manually if needed.
        _logger.warning("Could not drop column sale_order.pickup_slot_id: %s", exc)
