using ERPCore.Domain.Entities;
using ERPCore.Domain.Enums;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace ERPCore.Infra.Persistence.Configurations;

public sealed class DepartmentConfiguration : IEntityTypeConfiguration<Department>
{
    public void Configure(EntityTypeBuilder<Department> builder)
    {
        builder.ToTable("hr_departments");
        builder.HasKey(d => d.DepartmentId);

        builder.Property(d => d.Code).IsRequired().HasMaxLength(20);
        builder.HasIndex(d => d.Code).IsUnique();
        builder.Property(d => d.Name).IsRequired().HasMaxLength(200);

        builder.Property(d => d.Status)
            .HasConversion<string>().HasMaxLength(20).IsRequired()
            .HasDefaultValue(EntityStatus.Active);

        // Self-nesting (unlimited depth, unlike Category) — cycle prevention is
        // service-level, not a DB constraint (docs/12-BACKEND-HRM.md A.1/C.1).
        builder.HasOne(d => d.ParentDepartment).WithMany()
            .HasForeignKey(d => d.ParentDepartmentId).OnDelete(DeleteBehavior.Restrict);

        builder.HasOne(d => d.HeadEmployee).WithMany()
            .HasForeignKey(d => d.HeadEmployeeId).OnDelete(DeleteBehavior.Restrict);

        builder.HasOne(d => d.Branch).WithMany()
            .HasForeignKey(d => d.BranchId).OnDelete(DeleteBehavior.Restrict);

        builder.Property(d => d.CreatedAt).IsRequired();
        builder.Property(d => d.RowVersion).IsRowVersion();

        builder.HasIndex(d => d.Status);
        builder.HasIndex(d => d.ParentDepartmentId);
    }
}
