-- Tables affected: qt_configurations
-- recovery.not-started: check first; ADD COLUMN fails if pricelist_id already exists
-- recovery.partial: ALTER TABLE qt_configurations DROP COLUMN pricelist_id;
-- recovery.completed: no action needed
-- verify: pricelist_id column missing | SELECT 1 FROM information_schema.COLUMNS WHERE table_schema=DATABASE() AND table_name='qt_configurations' AND column_name='pricelist_id' HAVING COUNT(*)=0

-- Add pricelist binding to configurations
ALTER TABLE qt_configurations
    ADD COLUMN pricelist_id BIGINT UNSIGNED NULL AFTER server_count;

ALTER TABLE qt_configurations
    ADD INDEX idx_qt_configurations_pricelist_id (pricelist_id),
    ADD CONSTRAINT fk_qt_configurations_pricelist_id
        FOREIGN KEY (pricelist_id)
        REFERENCES qt_pricelists(id)
        ON DELETE RESTRICT
        ON UPDATE CASCADE;

-- Backfill existing configurations to latest active pricelist
SET @latest_active_pricelist_id := (
    SELECT id
    FROM qt_pricelists
    WHERE is_active = 1
    ORDER BY created_at DESC
    LIMIT 1
);

UPDATE qt_configurations
SET pricelist_id = @latest_active_pricelist_id
WHERE pricelist_id IS NULL
  AND @latest_active_pricelist_id IS NOT NULL;

-- Recalculate usage_count from configuration bindings
UPDATE qt_pricelists SET usage_count = 0;

UPDATE qt_pricelists pl
JOIN (
    SELECT pricelist_id, COUNT(*) AS cnt
    FROM qt_configurations
    WHERE pricelist_id IS NOT NULL
    GROUP BY pricelist_id
) cfg ON cfg.pricelist_id = pl.id
SET pl.usage_count = cfg.cnt;
