using Baya.Domain.Entities.Messaging;
using Baya.Domain.Entities.User;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Baya.Infrastructure.Persistence.Configuration.MessagingConfig;

/// <summary>
/// <c>ticket_participants</c> — who is on a thread. <c>UNIQUE(ticket_id, user_id)</c> is the authoritative
/// backstop against adding a user twice (a duplicate add is a clean conflict, never a raw DB error); removal is
/// a soft <c>removed_at</c> stamp, so the unique row survives and a re-add resurrects it. The
/// <c>(user_id, ticket_id)</c> index serves <c>ListMyTickets</c>.
/// </summary>
internal sealed class TicketParticipantConfig : IEntityTypeConfiguration<TicketParticipant>
{
    public void Configure(EntityTypeBuilder<TicketParticipant> builder)
    {
        builder.ToTable("TicketParticipants", "messaging");

        builder.Property(p => p.RoleOnTicket).HasMaxLength(20);

        builder.HasIndex(p => new { p.TicketId, p.UserId }).IsUnique();
        builder.HasIndex(p => new { p.UserId, p.TicketId });

        builder.HasOne<User>().WithMany().HasForeignKey(p => p.UserId).IsRequired();
        builder.HasOne<User>().WithMany().HasForeignKey(p => p.AddedById).IsRequired(false);
    }
}
