using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using WhatsAppService.Domain.AggregatesModel.AIAgentAggregate;

namespace WhatsAppService.Infrastructure.EntityConfigurations;

/// <summary>
/// EN: EF Core configuration for AIAgent entity.
/// VI: Cấu hình EF Core cho entity AIAgent.
/// </summary>
public class AIAgentEntityTypeConfiguration : IEntityTypeConfiguration<AIAgent>
{
    public void Configure(EntityTypeBuilder<AIAgent> builder)
    {
        builder.ToTable("ai_agents");
        builder.HasKey(e => e.Id);
        builder.Ignore(e => e.DomainEvents);

        builder.Property(e => e.Id).HasColumnName("id").IsRequired();
        builder.Property<Guid>("_shopId").HasColumnName("shop_id").IsRequired();
        builder.Property<string>("_agentName").HasColumnName("agent_name").HasMaxLength(200).IsRequired();
        builder.Property<Guid?>("_knowledgeBaseId").HasColumnName("knowledge_base_id");
        builder.Property<bool>("_isActive").HasColumnName("is_active").HasDefaultValue(false);
        builder.Property<int?>("_maxPromptTokens").HasColumnName("max_prompt_tokens");
        builder.Property<int?>("_maxCompletionTokens").HasColumnName("max_completion_tokens");
        builder.Property<decimal?>("_dailyBudgetUsd").HasColumnName("daily_budget_usd").HasPrecision(10, 2);
        builder.Property<decimal?>("_monthlyBudgetUsd").HasColumnName("monthly_budget_usd").HasPrecision(10, 2);
        builder.Property<DateTime>("_createdAt").HasColumnName("created_at").IsRequired();
        builder.Property<DateTime?>("_updatedAt").HasColumnName("updated_at");

        // EN: AgentPersonality as owned entity / VI: AgentPersonality như owned entity
        builder.OwnsOne<AgentPersonality>("_personality", personality =>
        {
            personality.Property(p => p.Tone).HasColumnName("personality_tone").HasMaxLength(50).HasDefaultValue("friendly");
            personality.Property(p => p.Language).HasColumnName("personality_language").HasMaxLength(20).HasDefaultValue("vietnamese");
            personality.Property(p => p.PromptTemplate).HasColumnName("prompt_template");
            
            // EN: Constraints stored as JSONB / VI: Constraints lưu dưới dạng JSONB
            personality.Property<string>("ConstraintsJson")
                .HasColumnName("personality_constraints")
                .HasColumnType("jsonb")
                .HasDefaultValueSql("'[]'::jsonb");
            
            personality.Ignore(p => p.Constraints);
        });

        builder.HasIndex("_shopId").HasDatabaseName("idx_ai_agents_shop");
        builder.HasIndex("_shopId", "_isActive").HasDatabaseName("idx_ai_agents_shop_active");
    }
}
