using Argus.Domain;
using Microsoft.EntityFrameworkCore;

namespace Argus.Data;

public sealed class ArgusDbContext(DbContextOptions<ArgusDbContext> options) : DbContext(options)
{
    public DbSet<CatalogApp> Apps => Set<CatalogApp>();

    public DbSet<AppRelease> Releases => Set<AppRelease>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<CatalogApp>(entity =>
        {
            entity.ToTable("Apps");
            entity.HasKey(x => x.Id);
            entity.Property(x => x.Slug).HasMaxLength(100).IsRequired();
            entity.Property(x => x.Name).HasMaxLength(160).IsRequired();
            entity.Property(x => x.Summary).HasMaxLength(280).IsRequired();
            entity.Property(x => x.Description).HasMaxLength(4_000).IsRequired();
            entity.Property(x => x.RepositoryUrl).HasMaxLength(500);
            entity.Property(x => x.HomepageUrl).HasMaxLength(500);
            entity.HasIndex(x => x.Slug).IsUnique();
            entity.HasIndex(x => new { x.IsListed, x.Name });
            entity.HasMany(x => x.Releases)
                .WithOne(x => x.CatalogApp)
                .HasForeignKey(x => x.CatalogAppId)
                .OnDelete(DeleteBehavior.Cascade);
        });

        modelBuilder.Entity<AppRelease>(entity =>
        {
            entity.ToTable("Releases");
            entity.HasKey(x => x.Id);
            entity.Property(x => x.Version).HasMaxLength(64).IsRequired();
            entity.Property(x => x.Channel).HasMaxLength(40).IsRequired();
            entity.Property(x => x.Platform).HasMaxLength(80).IsRequired();
            entity.Property(x => x.PackageKind).HasMaxLength(40).IsRequired();
            entity.Property(x => x.OriginalFileName).HasMaxLength(255).IsRequired();
            entity.Property(x => x.StoredRelativePath).HasMaxLength(255).IsRequired();
            entity.Property(x => x.ContentType).HasMaxLength(160).IsRequired();
            entity.Property(x => x.Sha256).HasMaxLength(64).IsRequired();
            entity.Property(x => x.Notes).HasMaxLength(4_000);
            entity.HasIndex(x => new { x.CatalogAppId, x.Version, x.Channel, x.Platform }).IsUnique();
            entity.HasIndex(x => new { x.CatalogAppId, x.PublishedAt });
            entity.HasIndex(x => x.PublishedAt);
        });
    }
}
