-- Phase 125-01: backfill invoice_requested z is_invoice + DROP COLUMN is_invoice
-- Idempotentna: guard przez information_schema.COLUMNS; no-op po pierwszym uruchomieniu.
-- Pattern z Key Decision 2026-05-10: migracje no-op zawsze jako DDL (ALTER TABLE COMMENT),
-- nigdy SELECT 1; (PDO unbuffered + result set -> SQLSTATE 2014).

SET @col_exists := (
  SELECT COUNT(*) FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'orders'
    AND COLUMN_NAME = 'is_invoice'
);

SET @sql_backfill := IF(@col_exists > 0,
  'UPDATE orders SET invoice_requested = 1 WHERE is_invoice = 1 AND invoice_requested = 0',
  'ALTER TABLE orders COMMENT = ''phase-125 backfill no-op'''
);
PREPARE stmt_backfill FROM @sql_backfill;
EXECUTE stmt_backfill;
DEALLOCATE PREPARE stmt_backfill;

SET @sql_drop := IF(@col_exists > 0,
  'ALTER TABLE orders DROP COLUMN is_invoice',
  'ALTER TABLE orders COMMENT = ''phase-125 drop no-op'''
);
PREPARE stmt_drop FROM @sql_drop;
EXECUTE stmt_drop;
DEALLOCATE PREPARE stmt_drop;
