SET @db := DATABASE();

SET @sql := (
  SELECT IF(
    EXISTS(
      SELECT 1 FROM information_schema.COLUMNS
      WHERE TABLE_SCHEMA=@db AND TABLE_NAME='cash_payments' AND COLUMN_NAME='payment_type'
    ),
    'SELECT 1',
    "ALTER TABLE cash_payments ADD COLUMN payment_type VARCHAR(20) NOT NULL DEFAULT 'party' AFTER account_source_type"
  )
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @sql := (
  SELECT IF(
    EXISTS(
      SELECT 1 FROM information_schema.COLUMNS
      WHERE TABLE_SCHEMA=@db AND TABLE_NAME='cash_payments' AND COLUMN_NAME='expense_item_id'
    ),
    'SELECT 1',
    "ALTER TABLE cash_payments ADD COLUMN expense_item_id INT NULL AFTER party_id"
  )
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @sql := (
  SELECT IF(
    EXISTS(
      SELECT 1 FROM information_schema.STATISTICS
      WHERE TABLE_SCHEMA=@db AND TABLE_NAME='cash_payments' AND INDEX_NAME='idx_cp_expense_item'
    ),
    'SELECT 1',
    'ALTER TABLE cash_payments ADD INDEX idx_cp_expense_item (expense_item_id)'
  )
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
