using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Watcher.Models;

namespace Watcher.Data;

public class AppDbContext : DbContext
{
    private readonly IConfiguration _configuration;

    public AppDbContext(DbContextOptions<AppDbContext> options, IConfiguration configuration)
        : base(options)
    {
        _configuration = configuration;
    }

    public DbSet<Container> Containers { get; set; }

    public DbSet<Server> Servers { get; set; }

    public DbSet<Image> Images { get; set; }

    public DbSet<LogEvent> LogEvents { get; set; }

    public DbSet<Metric> Metrics { get; set; }

    public DbSet<Tag> Tags { get; set; }

    public DbSet<User> Users { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            var provider = _configuration["Database:Provider"];

            if (provider == "MySql")
            {
                var connStr = _configuration.GetConnectionString("MySql")
                              ?? _configuration["Database:ConnectionStrings:MySql"];
                optionsBuilder.UseMySql(connStr, ServerVersion.AutoDetect(connStr));
            }
            else if (provider == "Sqlite")
            {
                var connStr = _configuration.GetConnectionString("Sqlite")
                              ?? _configuration["Database:ConnectionStrings:Sqlite"];
                optionsBuilder.UseSqlite(connStr);
            }
            else
            {
                throw new Exception("Unsupported database provider configured.");
            }
        }
    }
}

