using System.IO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using CMSMicroservice.Infrastructure.Persistence.Interceptors;

namespace CMSMicroservice.Infrastructure.Persistence;

/// <summary>
/// Factory برای ایجاد DbContext در زمان طراحی (migrations, scaffolding)
/// </summary>
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
    public ApplicationDbContext CreateDbContext(string[] args)
    {
        // سعی در خواندن connection string از appsettings.json
        var basePath = Directory.GetCurrentDirectory();
        var webApiPath = Path.Combine(basePath, "../CMSMicroservice.WebApi");
        
        if (Directory.Exists(webApiPath))
        {
            basePath = webApiPath;
        }
        
        var configuration = new ConfigurationBuilder()
            .SetBasePath(basePath)
            .AddJsonFile("appsettings.json", optional: true)
            .AddJsonFile("appsettings.Development.json", optional: true)
            .AddEnvironmentVariables()
            .Build();

        var connectionString = configuration.GetConnectionString("DefaultConnection");

        // اگر connection string پیدا نشد، از یک مقدار پیش‌فرض استفاده کن
        if (string.IsNullOrEmpty(connectionString))
        {
            connectionString = "Server=localhost;Database=CMS;Trusted_Connection=True;TrustServerCertificate=True;";
        }

        var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
        optionsBuilder.UseSqlServer(connectionString, 
            b => b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName));

        return new ApplicationDbContext(optionsBuilder.Options);
    }
}
