using Microsoft.EntityFrameworkCore;

namespace Nexus.Api.Data;

public sealed class NexusDbContext(DbContextOptions<NexusDbContext> options) : DbContext(options)
{
    public DbSet<Project> Projects => Set<Project>();
    public DbSet<WorkTask> Tasks => Set<WorkTask>();
    public DbSet<Notification> Notifications => Set<Notification>();
    public DbSet<ActivityEvent> Activity => Set<ActivityEvent>();
    public DbSet<NexusUser> Users => Set<NexusUser>();
    public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Project>().Property(x => x.Name).HasMaxLength(160);
        modelBuilder.Entity<WorkTask>(entity =>
        {
            entity.Property(x => x.Title).HasMaxLength(240);
            entity.Property(x => x.Detail).HasMaxLength(2000);
            entity.Property(x => x.Source).HasMaxLength(60);
            entity.Property(x => x.AssignedTo).HasMaxLength(60);
            entity.Property(x => x.ExpectedFrom).HasMaxLength(60);
            entity.HasIndex(x => x.Source);
            entity.HasIndex(x => x.AssignedTo);
            entity.HasIndex(x => x.IsAgentTask);
            entity.HasIndex(x => x.ExpectedFrom);
            entity.HasOne(x => x.ParentTask)
                  .WithMany(x => x.ChildTasks)
                  .HasForeignKey(x => x.ParentTaskId)
                  .OnDelete(DeleteBehavior.SetNull);
        });
        modelBuilder.Entity<Notification>(entity =>
        {
            entity.Property(x => x.Title).HasMaxLength(240);
            entity.Property(x => x.Message).HasMaxLength(1000);
            entity.Property(x => x.Type).HasMaxLength(60);
            entity.Property(x => x.ForUser).HasMaxLength(60);
            entity.HasIndex(x => new { x.ForUser, x.IsRead, x.CreatedAt });
        });

        modelBuilder.Entity<ActivityEvent>(entity =>
        {
            entity.Property(x => x.Message).HasMaxLength(1000);
            entity.HasIndex(x => x.TaskId);
        });
        modelBuilder.Entity<NexusUser>().HasIndex(u => u.NormalizedEmail).IsUnique();
        modelBuilder.Entity<RefreshToken>().HasIndex(r => r.TokenHash).IsUnique();
        modelBuilder.Entity<RefreshToken>().HasIndex(r => new { r.UserId, r.FamilyId });
        modelBuilder.Entity<RefreshToken>().Property(r => r.ConcurrencyStamp).IsConcurrencyToken();
        modelBuilder.Entity<RefreshToken>()
            .HasOne(r => r.User)
            .WithMany(u => u.RefreshTokens)
            .HasForeignKey(r => r.UserId)
            .OnDelete(DeleteBehavior.Cascade);

        modelBuilder.Entity<ActivityEvent>().HasIndex(x => x.CreatedAt);
    }
}
