package com.zcloud.personnel.positioning.config;

import org.flywaydb.core.api.MigrationInfo;
import org.flywaydb.core.api.MigrationVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Recovers the known partial MySQL migration left by V20260710_02.
 *
 * <p>The migration is idempotent and can be safely rerun after Flyway removes
 * its failed history entry. Other failed migrations are never repaired
 * automatically so that new database problems still stop application startup.</p>
 */
@Configuration
public class FlywayRecoveryConfiguration {

    private static final Logger LOGGER = LoggerFactory.getLogger(FlywayRecoveryConfiguration.class);
    private static final MigrationVersion RECOVERABLE_VERSION = MigrationVersion.fromVersion("20260710.02");

    @Bean
    public FlywayMigrationStrategy flywayMigrationStrategy() {
        return flyway -> {
            List<MigrationInfo> failedMigrations = Arrays.stream(flyway.info().all())
                    .filter(migration -> migration.getState().isFailed())
                    .collect(Collectors.toList());

            if (!failedMigrations.isEmpty()) {
                boolean onlyKnownFailure = failedMigrations.size() == 1
                        && RECOVERABLE_VERSION.equals(failedMigrations.get(0).getVersion());
                if (!onlyKnownFailure) {
                    String failedVersions = failedMigrations.stream()
                            .map(migration -> migration.getVersion() == null
                                    ? migration.getDescription()
                                    : migration.getVersion().toString())
                            .collect(Collectors.joining(", "));
                    throw new IllegalStateException(
                            "Flyway contains unsupported failed migrations: " + failedVersions);
                }

                LOGGER.warn("Repairing known failed Flyway migration {} before retry", RECOVERABLE_VERSION);
                flyway.repair();
            }

            flyway.migrate();
        };
    }
}
