using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using WishNinja.Data.Entities;

namespace WishNinja.Data;

public class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : IdentityDbContext<ApplicationUser>(options)
{
    public DbSet<Wishlist> Wishlists => Set<Wishlist>();
    public DbSet<WishlistShare> WishlistShares => Set<WishlistShare>();
    public DbSet<WishlistItem> WishlistItems => Set<WishlistItem>();
    public DbSet<Claim> Claims => Set<Claim>();
    public DbSet<Invite> Invites => Set<Invite>();

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<Wishlist>(e =>
        {
            e.HasOne(w => w.Owner)
                .WithMany()
                .HasForeignKey(w => w.OwnerId)
                .OnDelete(DeleteBehavior.Cascade);

            e.HasMany(w => w.Items)
                .WithOne(i => i.Wishlist!)
                .HasForeignKey(i => i.WishlistId)
                .OnDelete(DeleteBehavior.Cascade);

            e.HasMany(w => w.Shares)
                .WithOne(s => s.Wishlist!)
                .HasForeignKey(s => s.WishlistId)
                .OnDelete(DeleteBehavior.Cascade);

            e.HasIndex(w => w.OwnerId);
        });

        builder.Entity<WishlistShare>(e =>
        {
            e.HasOne(s => s.User)
                .WithMany()
                .HasForeignKey(s => s.UserId)
                .OnDelete(DeleteBehavior.Cascade);

            e.HasIndex(s => new { s.WishlistId, s.UserId }).IsUnique();
        });

        builder.Entity<WishlistItem>(e =>
        {
            e.HasMany(i => i.Claims)
                .WithOne(c => c.WishlistItem!)
                .HasForeignKey(c => c.WishlistItemId)
                .OnDelete(DeleteBehavior.Cascade);

            e.Property(i => i.Price).HasColumnType("decimal(18,2)");
            e.HasIndex(i => i.WishlistId);
        });

        builder.Entity<Claim>(e =>
        {
            e.HasOne(c => c.ClaimedByUser)
                .WithMany()
                .HasForeignKey(c => c.ClaimedByUserId)
                .OnDelete(DeleteBehavior.Cascade);

            e.HasIndex(c => c.WishlistItemId);
        });

        builder.Entity<Invite>(e =>
        {
            e.HasOne(i => i.InvitedByUser)
                .WithMany()
                .HasForeignKey(i => i.InvitedByUserId)
                .OnDelete(DeleteBehavior.Restrict);

            e.HasIndex(i => i.TokenHash);
            e.HasIndex(i => i.Email);
        });
    }
}
