-- Remove legacy aircraft_file_id from flight_inspection_file_checklists.
-- Current app writes helicopter_file_id; keeping aircraft_file_id as NOT NULL
-- causes inserts to fail with:
--   Error 1364 (HY000): Field 'aircraft_file_id' doesn't have a default value

SET @schema_name := DATABASE();

SELECT COUNT(*) INTO @has_legacy_fk
FROM information_schema.TABLE_CONSTRAINTS
WHERE TABLE_SCHEMA = @schema_name
  AND TABLE_NAME = 'flight_inspection_file_checklists'
  AND CONSTRAINT_TYPE = 'FOREIGN KEY'
  AND CONSTRAINT_NAME = 'fk_flight_inspection_file_checklists_aircraft_file';

SET @drop_legacy_fk_sql := IF(
  @has_legacy_fk > 0,
  'ALTER TABLE flight_inspection_file_checklists DROP FOREIGN KEY fk_flight_inspection_file_checklists_aircraft_file',
  'SELECT 1'
);
PREPARE stmt_drop_legacy_fk FROM @drop_legacy_fk_sql;
EXECUTE stmt_drop_legacy_fk;
DEALLOCATE PREPARE stmt_drop_legacy_fk;

SELECT COUNT(*) INTO @has_legacy_index
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @schema_name
  AND TABLE_NAME = 'flight_inspection_file_checklists'
  AND INDEX_NAME = 'fk_flight_inspection_file_checklists_aircraft_file';

SET @drop_legacy_index_sql := IF(
  @has_legacy_index > 0,
  'ALTER TABLE flight_inspection_file_checklists DROP INDEX fk_flight_inspection_file_checklists_aircraft_file',
  'SELECT 1'
);
PREPARE stmt_drop_legacy_index FROM @drop_legacy_index_sql;
EXECUTE stmt_drop_legacy_index;
DEALLOCATE PREPARE stmt_drop_legacy_index;

SELECT COUNT(*) INTO @has_legacy_column
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @schema_name
  AND TABLE_NAME = 'flight_inspection_file_checklists'
  AND COLUMN_NAME = 'aircraft_file_id';

SET @drop_legacy_column_sql := IF(
  @has_legacy_column > 0,
  'ALTER TABLE flight_inspection_file_checklists DROP COLUMN aircraft_file_id',
  'SELECT 1'
);
PREPARE stmt_drop_legacy_column FROM @drop_legacy_column_sql;
EXECUTE stmt_drop_legacy_column;
DEALLOCATE PREPARE stmt_drop_legacy_column;
