using ASTRAIN.Shared.Models;
using Microsoft.EntityFrameworkCore;

namespace ASTRAIN.Api.Data;

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

    public DbSet<User> Users => Set<User>();
    public DbSet<Exercise> Exercises => Set<Exercise>();
    public DbSet<Routine> Routines => Set<Routine>();
    public DbSet<RoutineExercise> RoutineExercises => Set<RoutineExercise>();
    public DbSet<RoutineRun> RoutineRuns => Set<RoutineRun>();
    public DbSet<RoutineRunEntry> RoutineRunEntries => Set<RoutineRunEntry>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .HasMany(u => u.Exercises)
            .WithOne(e => e.User)
            .HasForeignKey(e => e.UserId)
            .OnDelete(DeleteBehavior.Cascade);

        modelBuilder.Entity<User>()
            .HasMany(u => u.Routines)
            .WithOne(r => r.User)
            .HasForeignKey(r => r.UserId)
            .OnDelete(DeleteBehavior.Cascade);

        modelBuilder.Entity<RoutineExercise>()
            .HasIndex(re => new { re.RoutineId, re.Order })
            .IsUnique();

        modelBuilder.Entity<RoutineExercise>()
            .HasOne(re => re.Routine)
            .WithMany(r => r.Exercises)
            .HasForeignKey(re => re.RoutineId)
            .OnDelete(DeleteBehavior.Cascade);

        modelBuilder.Entity<RoutineExercise>()
            .HasOne(re => re.Exercise)
            .WithMany(e => e.RoutineExercises)
            .HasForeignKey(re => re.ExerciseId)
            .OnDelete(DeleteBehavior.Cascade);

        modelBuilder.Entity<RoutineRun>()
            .HasOne(rr => rr.Routine)
            .WithMany(r => r.Runs)
            .HasForeignKey(rr => rr.RoutineId)
            .OnDelete(DeleteBehavior.Cascade);

        modelBuilder.Entity<RoutineRunEntry>()
            .HasOne(rre => rre.RoutineRun)
            .WithMany(rr => rr.Entries)
            .HasForeignKey(rre => rre.RoutineRunId)
            .OnDelete(DeleteBehavior.Cascade);

        base.OnModelCreating(modelBuilder);
    }
}
