using Extrudex.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Extrudex.Infrastructure.Data.Configurations;

public class FilamentUsageConfiguration : BaseEntityConfiguration<FilamentUsage>
{
    public override void Configure(EntityTypeBuilder<FilamentUsage> builder)
    {
        base.Configure(builder);

        builder.Property(e => e.PrintJobId)
            .HasColumnName("print_job_id")
            .IsRequired();

        builder.Property(e => e.SpoolId)
            .HasColumnName("spool_id")
            .IsRequired();

        builder.Property(e => e.PrinterId)
            .HasColumnName("printer_id")
            .IsRequired();

        builder.Property(e => e.GramsUsed)
            .HasColumnName("grams_used")
            .HasPrecision(10, 2)
            .IsRequired();

        builder.Property(e => e.MmExtruded)
            .HasColumnName("mm_extruded")
            .HasPrecision(12, 2)
            .IsRequired();

        builder.Property(e => e.RecordedAt)
            .HasColumnName("recorded_at")
            .HasDefaultValueSql("now() at time zone 'utc'")
            .IsRequired();

        builder.Property(e => e.Notes)
            .HasColumnName("notes")
            .HasMaxLength(2000);

        // Index on print_job_id for querying usage by print job
        builder.HasIndex(e => e.PrintJobId)
            .HasDatabaseName("ix_filament_usages_print_job_id");

        // Index on spool_id for querying usage by spool (filament)
        builder.HasIndex(e => e.SpoolId)
            .HasDatabaseName("ix_filament_usages_spool_id");

        // Index on printer_id for querying usage by printer
        builder.HasIndex(e => e.PrinterId)
            .HasDatabaseName("ix_filament_usages_printer_id");

        // Index on recorded_at for time-range queries
        builder.HasIndex(e => e.RecordedAt)
            .HasDatabaseName("ix_filament_usages_recorded_at");

        // Composite index for querying usage by spool within a date range
        builder.HasIndex(e => new { e.SpoolId, e.RecordedAt })
            .HasDatabaseName("ix_filament_usages_spool_id_recorded_at");

        // Relationships
        builder.HasOne(e => e.PrintJob)
            .WithMany(e => e.FilamentUsages)
            .HasForeignKey(e => e.PrintJobId)
            .HasConstraintName("fk_filament_usages_print_job")
            .OnDelete(DeleteBehavior.Cascade);

        builder.HasOne(e => e.Spool)
            .WithMany(e => e.FilamentUsages)
            .HasForeignKey(e => e.SpoolId)
            .HasConstraintName("fk_filament_usages_spool")
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasOne(e => e.Printer)
            .WithMany(e => e.FilamentUsages)
            .HasForeignKey(e => e.PrinterId)
            .HasConstraintName("fk_filament_usages_printer")
            .OnDelete(DeleteBehavior.Restrict);
    }
}