using AdsManagerService.Domain.AggregatesModel.CampaignAggregate;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace AdsManagerService.Infrastructure.EntityConfigurations;

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

        builder.HasKey(c => c.Id);

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

        builder.Property(c => c.AdvertiserId)
            .HasColumnName("advertiser_id")
            .IsRequired();

        builder.Property(c => c.Name)
            .HasColumnName("name")
            .HasMaxLength(255)
            .IsRequired();

        builder.Property(c => c.Description)
            .HasColumnName("description")
            .HasMaxLength(1000);

        builder.Property(c => c.StatusId)
            .HasColumnName("status_id")
            .IsRequired();

        builder.Property(c => c.ObjectiveId)
            .HasColumnName("objective_id")
            .IsRequired();

        // Budget as owned type
        builder.OwnsOne(c => c.Budget, budget =>
        {
            budget.Property(b => b.Type)
                .HasColumnName("budget_type")
                .IsRequired();

            budget.Property(b => b.Amount)
                .HasColumnName("budget_amount")
                .HasColumnType("decimal(18,2)")
                .IsRequired();

            budget.Property(b => b.Currency)
                .HasColumnName("currency")
                .HasMaxLength(10)
                .IsRequired();
        });

        builder.Property(c => c.StartDate)
            .HasColumnName("start_date");

        builder.Property(c => c.EndDate)
            .HasColumnName("end_date");

        builder.Property(c => c.TotalSpend)
            .HasColumnName("total_spend")
            .HasColumnType("decimal(18,2)")
            .HasDefaultValue(0);

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

        builder.Property(c => c.UpdatedAt)
            .HasColumnName("updated_at");

        // Indexes
        builder.HasIndex(c => c.AdvertiserId).HasDatabaseName("idx_campaigns_advertiser_id");
        builder.HasIndex(c => c.StatusId).HasDatabaseName("idx_campaigns_status_id");
        builder.HasIndex(c => c.CreatedAt).HasDatabaseName("idx_campaigns_created_at");

        // Ignore navigation properties
        builder.Ignore(c => c.DomainEvents);
        builder.Ignore(c => c.Status);
        builder.Ignore(c => c.Objective);
    }
}
