using Knots.Models;
using Microsoft.EntityFrameworkCore;

namespace Knots;

public class KnotsDbContext : DbContext
{
    public DbSet<User> Users => Set<User>();
    public DbSet<Discussion> Discussions => Set<Discussion>();
    public DbSet<Group> Groups => Set<Group>();
    public DbSet<Message> Messages => Set<Message>();
    public DbSet<Role> Roles => Set<Role>();
    public DbSet<Key> Keys => Set<Key>();
    public DbSet<UserDiscussion> UserDiscussions => Set<UserDiscussion>();
    public DbSet<GroupUser> GroupUsers => Set<GroupUser>();

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        //Infos de connexion à la base de données
        string connectionString =
            "Server=romaric-thibault.fr;" +
            "Database=knots;" +
            "User Id=knots;" +
            "Password=knots;" +
            "TrustServerCertificate=true;";

        optionsBuilder.UseSqlServer(connectionString);
    }

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<GroupUser>()
            .HasKey(gu => new { gu.GroupId, gu.UserId });

        modelBuilder.Entity<GroupUser>()
            .HasOne(gu => gu.Group)
            .WithMany(g => g.GroupUsers)
            .HasForeignKey(gu => gu.GroupId)
            .OnDelete(DeleteBehavior.Cascade);

        modelBuilder.Entity<GroupUser>()
            .HasOne(gu => gu.User)
            .WithMany()
            .HasForeignKey(gu => gu.UserId)
            .OnDelete(DeleteBehavior.Restrict);

        modelBuilder.Entity<GroupUser>()
            .HasOne(gu => gu.Role)
            .WithMany(r => r.GroupUsers)
            .HasForeignKey(gu => gu.RoleId);
        
        modelBuilder.Entity<Discussion>()
            .HasOne(d => d.Group)
            .WithMany()
            .HasForeignKey(d => d.GroupId)
            .OnDelete(DeleteBehavior.Restrict);
        
        modelBuilder.Entity<Group>()
            .HasOne(g => g.Discussion)
            .WithMany()
            .HasForeignKey(g => g.DiscussionId)
            .OnDelete(DeleteBehavior.Restrict);
        
        modelBuilder.Entity<UserDiscussion>()
            .HasKey(ud => new { ud.UserId, ud.DiscussionId });

        modelBuilder.Entity<UserDiscussion>()
            .HasOne(ud => ud.Discussion)
            .WithMany(d => d.UserDiscussions)
            .HasForeignKey(ud => ud.DiscussionId)
            .OnDelete(DeleteBehavior.Cascade);

        modelBuilder.Entity<UserDiscussion>()
            .HasOne(ud => ud.User)
            .WithMany(u => u.UserDiscussions)
            .HasForeignKey(ud => ud.UserId)
            .OnDelete(DeleteBehavior.Restrict);
    }
}