using Health.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

namespace Health.WebApi.Data;

/// <summary>
/// 设计时 DbContext 工厂——仅供 dotnet-ef（migrations / database update）使用。
/// 不会启动 Web 服务或后台 Worker，只负责构建 AppDbContext 的连接配置。
/// 连接串优先级：DB_CONNECTION 环境变量 → backend/.env 文件 → 本地默认。
/// </summary>
public sealed class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
    private const string FallbackConnection =
        "Host=localhost;Database=health_manager;Username=postgres;Password=postgres123";

    public AppDbContext CreateDbContext(string[] args)
    {
        var connection = Environment.GetEnvironmentVariable("DB_CONNECTION")
            ?? ReadConnectionFromEnvFile()
            ?? FallbackConnection;

        var options = new DbContextOptionsBuilder<AppDbContext>()
            .UseNpgsql(connection)
            .Options;

        return new AppDbContext(options);
    }

    // 从 backend 目录的 .env 读取 DB_CONNECTION（设计时不走 Program.cs 的加载逻辑）
    private static string? ReadConnectionFromEnvFile()
    {
        var dir = new DirectoryInfo(Directory.GetCurrentDirectory());
        for (var i = 0; i < 6 && dir != null; i++, dir = dir.Parent)
        {
            var envPath = Path.Combine(dir.FullName, ".env");
            if (!File.Exists(envPath)) continue;

            foreach (var line in File.ReadAllLines(envPath))
            {
                var trimmed = line.Trim();
                if (trimmed.Length == 0 || trimmed.StartsWith('#')) continue;
                var eq = trimmed.IndexOf('=');
                if (eq <= 0) continue;
                if (trimmed[..eq].Trim() != "DB_CONNECTION") continue;
                var value = trimmed[(eq + 1)..].Trim();
                return value.Length > 0 ? value : null;
            }
        }
        return null;
    }
}
