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

namespace AdsManagerService.Infrastructure.EntityConfigurations;

public class AdSetEntityTypeConfiguration : IEntityTypeConfiguration<AdSet>
{
    public void Configure(EntityTypeBuilder<AdSet> builder)
    {
        builder.ToTable("ad_sets");

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

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

        builder.Property(a => a.CampaignId)
            .HasColumnName("campaign_id")
            .IsRequired();

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

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

        // Targeting as owned type
        builder.OwnsOne(a => a.Targeting, targeting =>
        {
            targeting.Property(t => t.MinAge).HasColumnName("target_min_age");
            targeting.Property(t => t.MaxAge).HasColumnName("target_max_age");
            targeting.Property(t => t.Genders).HasColumnName("target_genders").HasMaxLength(50);
            targeting.Property(t => t.Locations).HasColumnName("target_locations").HasMaxLength(500);
            targeting.Property(t => t.Interests).HasColumnName("target_interests").HasMaxLength(500);
            targeting.Property(t => t.CustomAudienceIds).HasColumnName("custom_audience_ids").HasMaxLength(500);
            targeting.Property(t => t.LookalikeAudienceIds).HasColumnName("lookalike_audience_ids").HasMaxLength(500);
        });

        // BidStrategy as owned type
        builder.OwnsOne(a => a.BidStrategy, bidStrategy =>
        {
            bidStrategy.Property(b => b.Type).HasColumnName("bid_type").IsRequired();
            bidStrategy.Property(b => b.BidAmount).HasColumnName("bid_amount").HasColumnType("decimal(18,6)");
            bidStrategy.Property(b => b.TargetCost).HasColumnName("target_cost").HasColumnType("decimal(18,6)");
        });

        builder.Property(a => a.DailyBudget)
            .HasColumnName("daily_budget")
            .HasColumnType("decimal(18,2)")
            .IsRequired();

        builder.Property(a => a.StartDate).HasColumnName("start_date");
        builder.Property(a => a.EndDate).HasColumnName("end_date");
        builder.Property(a => a.CreatedAt).HasColumnName("created_at").IsRequired();
        builder.Property(a => a.UpdatedAt).HasColumnName("updated_at");

        // Indexes
        builder.HasIndex(a => a.CampaignId).HasDatabaseName("idx_ad_sets_campaign_id");
        builder.HasIndex(a => a.StatusId).HasDatabaseName("idx_ad_sets_status_id");

        builder.Ignore(a => a.DomainEvents);
        builder.Ignore(a => a.Status);
    }
}
