package com.lingniu.ingest.identity.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lingniu.ingest.identity.MySqlVehicleIdentityService;
import com.lingniu.ingest.identity.VehicleIdentityRegistry;
import com.lingniu.ingest.identity.VehicleIdentityResolver;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
import java.util.Locale;

@AutoConfiguration
@EnableConfigurationProperties(VehicleIdentityProperties.class)
public class VehicleIdentityAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public ObjectMapper vehicleIdentityObjectMapper() {
        return new ObjectMapper();
    }

    @Bean
    @ConditionalOnMissingBean({VehicleIdentityResolver.class, VehicleIdentityRegistry.class})
    public MySqlVehicleIdentityService mysqlVehicleIdentityService(VehicleIdentityProperties properties,
                                                                   ObjectMapper objectMapper) {
        requireMysqlStore(properties.getStore());
        VehicleIdentityProperties.Mysql mysql = properties.getMysql();
        DataSource dataSource = new DriverManagerDataSource(
                mysql.getJdbcUrl(), mysql.getUsername(), mysql.getPassword());
        return new MySqlVehicleIdentityService(dataSource, mysql, objectMapper);
    }

    private static void requireMysqlStore(String value) {
        String store = value == null || value.isBlank() ? "mysql" : value.trim().toLowerCase(Locale.ROOT);
        if (!"mysql".equals(store)) {
            throw new IllegalStateException("identity.store supports only mysql; configured value: " + value);
        }
    }
}
