using Microsoft.EntityFrameworkCore;
using NexusRMM.Core.Models;

namespace NexusRMM.Infrastructure.Data;

public class RmmDbContext : DbContext
{
    public RmmDbContext(DbContextOptions<RmmDbContext> options) : base(options) { }

    public DbSet<Agent> Agents => Set<Agent>();
    public DbSet<AgentMetric> AgentMetrics => Set<AgentMetric>();
    public DbSet<TaskItem> Tasks => Set<TaskItem>();
    public DbSet<Ticket> Tickets => Set<Ticket>();
    public DbSet<AlertRule> AlertRules => Set<AlertRule>();
    public DbSet<Alert> Alerts => Set<Alert>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Agent>(e =>
        {
            e.HasKey(a => a.Id);
            e.Property(a => a.Tags).HasColumnType("jsonb");
            e.HasIndex(a => a.Hostname);
            e.HasIndex(a => a.MacAddress);
        });

        modelBuilder.Entity<AgentMetric>(e =>
        {
            e.HasKey(m => m.Id);
            e.Property(m => m.Metrics).HasColumnType("jsonb");
            e.HasIndex(m => m.Timestamp);
            e.HasOne(m => m.Agent).WithMany(a => a.Metrics).HasForeignKey(m => m.AgentId);
        });

        modelBuilder.Entity<TaskItem>(e =>
        {
            e.HasKey(t => t.Id);
            e.Property(t => t.Payload).HasColumnType("jsonb");
            e.Property(t => t.Result).HasColumnType("jsonb");
            e.HasOne(t => t.Agent).WithMany(a => a.Tasks).HasForeignKey(t => t.AgentId);
        });

        modelBuilder.Entity<Ticket>(e =>
        {
            e.HasKey(t => t.Id);
            e.HasOne(t => t.Agent).WithMany(a => a.Tickets).HasForeignKey(t => t.AgentId);
        });

        modelBuilder.Entity<AlertRule>(e =>
        {
            e.HasKey(r => r.Id);
        });

        modelBuilder.Entity<Alert>(e =>
        {
            e.HasKey(a => a.Id);
            e.HasIndex(a => a.CreatedAt);
            e.HasOne(a => a.Rule).WithMany(r => r.Alerts).HasForeignKey(a => a.RuleId);
            e.HasOne(a => a.Agent).WithMany(a => a.Alerts).HasForeignKey(a => a.AgentId);
        });
    }
}
