using Microsoft.EntityFrameworkCore;

namespace RobotNet.MapManager.Data;


public class MapEditorDbContext(DbContextOptions<MapEditorDbContext> options) : DbContext(options)
{
    public DbSet<Map> Maps { get; private set; }
    public DbSet<Node> Nodes { get; private set; }
    public DbSet<Edge> Edges { get; private set; }
    public DbSet<Zone> Zones { get; private set; }
    public DbSet<Action> Actions { get; private set; }
    public DbSet<ElementModel> ElementModels { get; private set; }
    public DbSet<Element> Elements { get; private set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Map>()
            .HasMany(e => e.Actions)
            .WithOne(e => e.Map)
            .HasForeignKey(e => e.MapId)
            .OnDelete(DeleteBehavior.Restrict)
            .IsRequired();

        modelBuilder.Entity<Map>()
            .HasMany(e => e.Edges)
            .WithOne(e => e.Map)
            .HasForeignKey(e => e.MapId)
            .OnDelete(DeleteBehavior.Restrict)
            .IsRequired();

        modelBuilder.Entity<Map>()
            .HasMany(e => e.Nodes)
            .WithOne(e => e.Map)
            .HasForeignKey(e => e.MapId)
            .OnDelete(DeleteBehavior.Restrict)
            .IsRequired();

        modelBuilder.Entity<Map>()
            .HasMany(e => e.Zones)
            .WithOne(e => e.Map)
            .HasForeignKey(e => e.MapId)
            .OnDelete(DeleteBehavior.Restrict)
            .IsRequired();

        modelBuilder.Entity<Edge>()
            .HasOne(e => e.StartNode)
            .WithMany(n => n.StartEdges)
            .HasForeignKey(e => e.StartNodeId)
            .OnDelete(DeleteBehavior.Restrict)
            .IsRequired();

        modelBuilder.Entity<Edge>()
            .HasOne(e => e.EndNode)
            .WithMany(n => n.EndEdges)
            .HasForeignKey(e => e.EndNodeId)
            .OnDelete(DeleteBehavior.Restrict)
            .IsRequired();

        modelBuilder.Entity<Map>()
            .HasMany(e => e.ElementModels)
            .WithOne(e => e.Map)
            .HasForeignKey(e => e.MapId)
            .OnDelete(DeleteBehavior.Restrict)
            .IsRequired();

        modelBuilder.Entity<Map>()
            .HasMany(e => e.Elements)
            .WithOne(e => e.Map)
            .HasForeignKey(e => e.MapId)
            .OnDelete(DeleteBehavior.Restrict)
            .IsRequired();

        modelBuilder.Entity<Node>()
            .HasOne(n => n.Element)
            .WithOne(e => e.Node)
            .HasForeignKey<Element>(e => e.NodeId)
            .OnDelete(DeleteBehavior.Restrict)
            .IsRequired();

        modelBuilder.Entity<ElementModel>()
            .HasMany(e => e.Elements)
            .WithOne(e => e.Model)
            .HasForeignKey(e => e.ModelId)
            .OnDelete(DeleteBehavior.Restrict)
            .IsRequired();

        base.OnModelCreating(modelBuilder);
    }
}