using Domain.Entities.Forum.Boards;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Infrastructure.Persistence.Configurations.Forum.Boards;

public sealed class BoardConfiguration : IEntityTypeConfiguration<Board>
{
    public void Configure(EntityTypeBuilder<Board> builder)
    {
        builder.HasIndex(x => x.BoardGroupID);
        builder.HasIndex(x => x.Code).IsUnique();
        builder.HasIndex(x => x.Name);
        builder.HasIndex(x => x.Order);
        builder.HasIndex(x => x.IsSearch);
        builder.HasIndex(x => x.IsActive);
        builder.HasIndex(x => x.Posts);
        builder.HasIndex(x => x.Comments);
        builder.HasIndex(x => new { x.IsSearch, x.IsActive });
        builder.HasIndex(x => new { x.Code, x.IsSearch });
        builder.HasIndex(x => new { x.Code, x.IsActive });
        builder.HasIndex(x => x.CoinID);

        builder.HasOne(x => x.BoardGroup).WithMany().HasForeignKey(x => x.BoardGroupID).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne(x => x.BoardMeta).WithOne().HasForeignKey<BoardMeta>(x => x.BoardID).OnDelete(DeleteBehavior.Cascade);
        builder.HasMany(x => x.BoardManager).WithOne(x => x.Board).HasForeignKey(x => x.BoardID).OnDelete(DeleteBehavior.Cascade);
        builder.HasMany(x => x.BoardPrefix).WithOne(x => x.Board).HasForeignKey(x => x.BoardID).OnDelete(DeleteBehavior.Cascade);
        builder.HasMany(x => x.Post).WithOne(x => x.Board).HasForeignKey(x => x.BoardID).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne(x => x.Coin).WithMany().HasForeignKey(x => x.CoinID).OnDelete(DeleteBehavior.SetNull);

        builder.ToTable(nameof(Board), x => x.HasComment("게시판"));
        builder.HasKey(x => x.ID);
        builder.Property(x => x.ID).ValueGeneratedOnAdd().HasComment("PK");
        builder.Property(x => x.BoardGroupID).IsRequired().HasComment("분류 ID");
        builder.Property(x => x.Code).HasMaxLength(30).IsRequired().HasComment("게시판 주소");
        builder.Property(x => x.Name).HasMaxLength(70).IsRequired().HasComment("게시판 이름");
        builder.Property(x => x.Order).IsRequired().HasComment("순서");
        builder.Property(x => x.IsSearch).IsRequired().HasComment("검색 여부");
        builder.Property(x => x.IsActive).IsRequired().HasComment("사용 여부");
        builder.Property(x => x.Posts).IsRequired().HasComment("게시글 수");
        builder.Property(x => x.Comments).IsRequired().HasComment("댓글 수");
        builder.Property(x => x.UpdatedAt).HasComment("수정 일시");
        builder.Property(x => x.CreatedAt).IsRequired().HasComment("등록 일시");
    }
}
