package com.tasteby.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;

import javax.sql.DataSource;
import jakarta.annotation.PostConstruct;

@Configuration
public class DataSourceConfig {

    private static final Logger log = LoggerFactory.getLogger(DataSourceConfig.class);

    @Value("${app.oracle.wallet-path:}")
    private String walletPath;

    private final DataSource dataSource;

    public DataSourceConfig(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @PostConstruct
    public void configureWallet() {
        if (walletPath != null && !walletPath.isBlank()) {
            System.setProperty("oracle.net.tns_admin", walletPath);
            System.setProperty("oracle.net.wallet_location", walletPath);
        }
    }

    @EventListener(ApplicationReadyEvent.class)
    public void runMigrations() {
        migrate("ALTER TABLE restaurants ADD (tabling_url VARCHAR2(500))");
        migrate("ALTER TABLE restaurants ADD (catchtable_url VARCHAR2(500))");
    }

    private void migrate(String sql) {
        try (var conn = dataSource.getConnection(); var stmt = conn.createStatement()) {
            stmt.execute(sql);
            log.info("[MIGRATE] {}", sql);
        } catch (Exception e) {
            if (e.getMessage() != null && e.getMessage().contains("ORA-01430")) {
                log.debug("[MIGRATE] already done: {}", sql);
            } else {
                log.warn("[MIGRATE] failed: {} - {}", sql, e.getMessage());
            }
        }
    }
}
