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<ContainerMetric> ContainerMetrics { get; set; }

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

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            // Nur SQLite wird unterstützt
            var connStr = _configuration.GetConnectionString("Sqlite")
                          ?? _configuration["Database:ConnectionStrings:Sqlite"]
                          ?? "Data Source=./persistence/watcher.db";
            optionsBuilder.UseSqlite(connStr);
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        // Server IDs bei 0 starten lassen (statt Standard 1)
        modelBuilder.Entity<Server>()
            .Property(s => s.Id)
            .ValueGeneratedOnAdd();

        // SQLite-spezifische Konfiguration: AUTOINCREMENT startet bei 0
        modelBuilder.Entity<Server>()
            .ToTable(tb => tb.HasCheckConstraint("CK_Server_Id", "Id >= 0"));
    }
}

