using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using SteUp.Shared.Core.Entities;

namespace SteUp.Data.LocalDb;

public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
    public DbSet<Ispezione> Ispezioni => Set<Ispezione>();
    public DbSet<Scheda> Schede => Set<Scheda>();
    public DbSet<SchedaArticolo> SchedaArticoli => Set<SchedaArticolo>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Ispezione>()
            .HasKey(x => new { x.CodMdep, x.Data, x.Rilevatore });

        modelBuilder.Entity<Scheda>()
            .HasOne(x => x.Ispezione)
            .WithMany(x => x.Schede)
            .HasForeignKey(x => new { x.CodMdep, x.Data, x.Rilevatore })
            .OnDelete(DeleteBehavior.Cascade);

        modelBuilder.Entity<Scheda>()
            .HasIndex(x => new { x.CodMdep, x.Data, x.Rilevatore });

        modelBuilder.Entity<Scheda>()
            .Property(x => x.ImageNames)
            .HasConversion(
                v => JsonSerializer.Serialize(v, (JsonSerializerOptions?)null),
                v => JsonSerializer.Deserialize<List<string>>(v, (JsonSerializerOptions?)null) ?? new List<string>()
            );

        modelBuilder.Entity<SchedaArticolo>()
            .HasOne(a => a.Scheda)
            .WithMany(s => s.Articoli)
            .HasForeignKey(a => a.SchedaId)
            .OnDelete(DeleteBehavior.Cascade);

        modelBuilder.Entity<SchedaArticolo>()
            .HasIndex(a => new { a.SchedaId, a.Barcode })
            .IsUnique();
    }
}