-- +goose Up
-- Allow takeover_acs.base_id to be nullable so takeover can be created without base data.

SET @schema_name := DATABASE();

SELECT COUNT(*) INTO @takeover_acs_has_base_id
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @schema_name
  AND TABLE_NAME = 'takeover_acs'
  AND COLUMN_NAME = 'base_id';

SELECT COUNT(*) INTO @takeover_acs_base_id_is_nullable
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @schema_name
  AND TABLE_NAME = 'takeover_acs'
  AND COLUMN_NAME = 'base_id'
  AND IS_NULLABLE = 'YES';

SET @alter_takeover_acs_base_id_sql := IF(
  @takeover_acs_has_base_id = 1 AND @takeover_acs_base_id_is_nullable = 0,
  'ALTER TABLE takeover_acs MODIFY COLUMN base_id BINARY(16) NULL',
  'SELECT 1'
);
PREPARE stmt_alter_takeover_acs_base_id FROM @alter_takeover_acs_base_id_sql;
EXECUTE stmt_alter_takeover_acs_base_id;
DEALLOCATE PREPARE stmt_alter_takeover_acs_base_id;

-- +goose Down
-- Only restore NOT NULL when there are no NULL rows, so rollback stays safe.

SET @schema_name := DATABASE();

SELECT COUNT(*) INTO @takeover_acs_has_base_id
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @schema_name
  AND TABLE_NAME = 'takeover_acs'
  AND COLUMN_NAME = 'base_id';

SELECT COUNT(*) INTO @takeover_acs_null_base_rows
FROM takeover_acs
WHERE base_id IS NULL
  AND deleted_at IS NULL;

SELECT COUNT(*) INTO @takeover_acs_base_id_is_nullable
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @schema_name
  AND TABLE_NAME = 'takeover_acs'
  AND COLUMN_NAME = 'base_id'
  AND IS_NULLABLE = 'YES';

SET @restore_takeover_acs_base_id_sql := IF(
  @takeover_acs_has_base_id = 1 AND @takeover_acs_base_id_is_nullable = 1 AND @takeover_acs_null_base_rows = 0,
  'ALTER TABLE takeover_acs MODIFY COLUMN base_id BINARY(16) NOT NULL',
  'SELECT 1'
);
PREPARE stmt_restore_takeover_acs_base_id FROM @restore_takeover_acs_base_id_sql;
EXECUTE stmt_restore_takeover_acs_base_id;
DEALLOCATE PREPARE stmt_restore_takeover_acs_base_id;
