package com.saas.shared.core;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Statement;

@Slf4j
@Component
@Order(1)
@RequiredArgsConstructor
public class SchemaInitializer {

    private final DataSource dataSource;

    @Value("${multitenancy.admin-schema}")
    private String adminSchema;

    @PostConstruct
    public void initializeSchemas() {
        try (Connection connection = dataSource.getConnection();
             Statement statement = connection.createStatement()) {
            
            log.info("Initializing admin database: {}", adminSchema);
            
            String createSchemaSQL = String.format("CREATE DATABASE IF NOT EXISTS %s", adminSchema);
            statement.execute(createSchemaSQL);
            log.info("Admin database '{}' created or already exists", adminSchema);
            
            statement.execute(String.format("USE %s", adminSchema));
            log.info("Switched to admin database '{}'", adminSchema);
            
            log.info("Database initialization completed! Hibernate will handle table creation with ddl-auto");
            
        } catch (Exception e) {
            log.error("Failed to initialize admin database", e);
            throw new RuntimeException("Database initialization failed", e);
        }
    }
}
