using ColaFlow.Modules.Identity.Domain.Aggregates.Users;
using ColaFlow.Modules.Identity.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace ColaFlow.Modules.Identity.Infrastructure.Persistence.Configurations;

public class PasswordResetTokenConfiguration : IEntityTypeConfiguration<PasswordResetToken>
{
    public void Configure(EntityTypeBuilder<PasswordResetToken> builder)
    {
        builder.ToTable("password_reset_tokens");

        // Primary Key
        builder.HasKey(t => t.Id);
        builder.Property(t => t.Id).HasColumnName("id");

        // User ID (foreign key) - stored as Guid, mapped to UserId value object
        builder.Property(t => t.UserId)
            .HasConversion(
                userId => (Guid)userId,
                value => UserId.Create(value))
            .IsRequired()
            .HasColumnName("user_id");

        // Token hash (SHA-256)
        builder.Property(t => t.TokenHash)
            .HasMaxLength(64)
            .IsRequired()
            .HasColumnName("token_hash");

        // Timestamps
        builder.Property(t => t.ExpiresAt)
            .IsRequired()
            .HasColumnName("expires_at");

        builder.Property(t => t.CreatedAt)
            .IsRequired()
            .HasColumnName("created_at");

        builder.Property(t => t.UsedAt)
            .HasColumnName("used_at");

        // Security audit fields
        builder.Property(t => t.IpAddress)
            .HasMaxLength(45) // IPv6 max length
            .HasColumnName("ip_address");

        builder.Property(t => t.UserAgent)
            .HasMaxLength(500)
            .HasColumnName("user_agent");

        // Indexes for performance
        builder.HasIndex(t => t.TokenHash)
            .HasDatabaseName("ix_password_reset_tokens_token_hash");

        builder.HasIndex(t => t.UserId)
            .HasDatabaseName("ix_password_reset_tokens_user_id");

        // Composite index for finding active tokens
        builder.HasIndex(t => new { t.UserId, t.ExpiresAt, t.UsedAt })
            .HasDatabaseName("ix_password_reset_tokens_user_active");
    }
}
