using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace CSR.Infrastructure.Persistence
{
  public class CSRDbContextFactory : IDesignTimeDbContextFactory<CSRDbContext>
  {
    public CSRDbContext CreateDbContext(string[] args)
    {
      // build configuration.
      var configuration = new ConfigurationBuilder()
          .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "..", "CSR.WebUI"))
          .AddJsonFile("appsettings.json", optional: true)
          .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development"}.json", optional: true)
          .AddEnvironmentVariables()
          .AddKeyPerFile("/run/secrets", optional: true)
          .Build();

      // get the database path
      var dbPath = configuration["Database:Path"];
      if (string.IsNullOrEmpty(dbPath))
      {
        var folder = Environment.SpecialFolder.LocalApplicationData;
        var path = Environment.GetFolderPath(folder);
        dbPath = Path.Join(path, "csr.db");
      }

      // create DbContextOptions
      var optionsBuilder = new DbContextOptionsBuilder<CSRDbContext>();
      optionsBuilder.UseSqlite($"Data Source={dbPath}");

      return new CSRDbContext(optionsBuilder.Options);
    }
  }
}
