package com.saas.shared.core;

import org.hibernate.cfg.AvailableSettings;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * Configuration for Hibernate multi-tenancy using SCHEMA strategy.
 * This configures database-per-tenant isolation for MySQL.
 */
@Configuration
public class MultiTenantConfig {

    @Value("${spring.jpa.properties.hibernate.dialect:org.hibernate.dialect.MySQLDialect}")
    private String hibernateDialect;

    @Bean
    public HibernatePropertiesCustomizer hibernatePropertiesCustomizer(
            SchemaMultiTenantConnectionProvider connectionProvider,
            TenantIdentifierResolverImpl tenantResolver) {
        return (Map<String, Object> hibernateProperties) -> {
            hibernateProperties.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, connectionProvider);
            hibernateProperties.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, tenantResolver);
            hibernateProperties.put("hibernate.multiTenancy", "SCHEMA");
            hibernateProperties.put(AvailableSettings.DIALECT, hibernateDialect);
            
            System.out.println("🔧 MultiTenantConfig: Hibernate multi-tenancy SCHEMA strategy configured");
        };
    }
}
