using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using MissionService.Domain.AggregatesModel.CheckInAggregate;

namespace MissionService.Infrastructure.EntityConfigurations;

/// <summary>
/// EN: EF Core configuration for UserCheckIn aggregate root
/// VI: Cấu hình EF Core cho UserCheckIn aggregate root
/// </summary>
public class UserCheckInEntityTypeConfiguration : IEntityTypeConfiguration<UserCheckIn>
{
    public void Configure(EntityTypeBuilder<UserCheckIn> builder)
    {
        builder.ToTable("user_checkins");

        builder.HasKey(c => c.Id);
        
        builder.Property(c => c.Id)
            .HasColumnName("id")
            .ValueGeneratedNever();

        builder.Property(c => c.UserId)
            .HasColumnName("user_id")
            .IsRequired();
        
        // EN: Unique index - one check-in profile per user
        // VI: Index duy nhất - mỗi user chỉ có một hồ sơ check-in
        builder.HasIndex(c => c.UserId)
            .IsUnique();

        builder.Property(c => c.CurrentStreak)
            .HasColumnName("current_streak");

        builder.Property(c => c.LongestStreak)
            .HasColumnName("longest_streak");

        builder.Property(c => c.TotalCheckIns)
            .HasColumnName("total_checkins");

        builder.Property(c => c.LastCheckInDate)
            .HasColumnName("last_checkin_date");

        // EN: Navigation to check-in days / VI: Navigation đến các ngày check-in
        builder.HasMany(c => c.CheckInDays)
            .WithOne()
            .HasForeignKey("user_checkin_id")
            .OnDelete(DeleteBehavior.Cascade);

        builder.Navigation(c => c.CheckInDays)
            .UsePropertyAccessMode(PropertyAccessMode.Field);
    }
}

/// <summary>
/// EN: EF Core configuration for CheckInDay entity
/// VI: Cấu hình EF Core cho CheckInDay entity
/// </summary>
public class CheckInDayEntityTypeConfiguration : IEntityTypeConfiguration<CheckInDay>
{
    public void Configure(EntityTypeBuilder<CheckInDay> builder)
    {
        builder.ToTable("checkin_days");

        builder.HasKey(d => d.Id);
        
        builder.Property(d => d.Id)
            .HasColumnName("id")
            .ValueGeneratedNever();

        builder.Property<Guid>("user_checkin_id");

        builder.Property(d => d.Date)
            .HasColumnName("date")
            .IsRequired();
        
        // EN: Index on user_checkin_id + date for faster lookups
        // VI: Index cho user_checkin_id + date để tra cứu nhanh hơn
        builder.HasIndex("user_checkin_id", "Date")
            .IsUnique();

        builder.Property(d => d.PointsEarned)
            .HasColumnName("points_earned")
            .HasPrecision(18, 2);

        builder.Property(d => d.IsMilestone)
            .HasColumnName("is_milestone");

        builder.Property(d => d.StreakOnDay)
            .HasColumnName("streak_on_day");
    }
}
