using Knots.Models;
using Microsoft.EntityFrameworkCore;

namespace Knots;

public class KnotsDbContext : DbContext
{
    public DbSet<Discussion> Discussions { get; set; }
    public DbSet<UserDiscussion> UserDiscussions { get; set; }
    public DbSet<Group> Groups { get; set; }
    public DbSet<Key> Keys { get; set; }
    public DbSet<Message> Messages { get; set; }
    public DbSet<Role> Roles { get; set; }
    public DbSet<User> Users { get; set; }

    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<UserDiscussion>()
            .HasKey(ud => new { ud.UserId, ud.DiscussionId });

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

        modelBuilder.Entity<UserDiscussion>()
            .HasOne(ud => ud.Discussion)
            .WithMany(d => d.UserDiscussions)
            .HasForeignKey(ud => ud.DiscussionId);
        
        modelBuilder.Entity<Message>()
            .HasOne(m => m.Discussion)
            .WithMany(d => d.Messages)
            .HasForeignKey(m => m.DiscussionId);

        modelBuilder.Entity<Message>()
            .HasOne(m => m.User)
            .WithMany(u => u.Messages)
            .HasForeignKey(m => m.UserId);
        
        modelBuilder.Entity<Group>()
            .HasOne(g => g.Discussion)
            .WithOne(d => d.Group)
            .HasForeignKey<Group>(g => g.DiscussionId);
    }
}