using Microsoft.EntityFrameworkCore;
using PageFetcher.Data.Entities;

namespace PageFetcher.Data;

/// <summary>
/// EF Core DbContext for the <c>pageFetcher</c> schema.
/// Owns the <c>PageFetches</c> audit table.
/// </summary>
public sealed class PageFetchDbContext : DbContext
{
    public const string SchemaName = MigrationConstants.SchemaName;
    public const string MigrationTableName = MigrationConstants.MigrationTableName;

    public PageFetchDbContext(DbContextOptions<PageFetchDbContext> options) : base(options) { }

    public DbSet<PageFetchEntity> PageFetches => Set<PageFetchEntity>();

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
        optionsBuilder.UseSqlServer(x => x.MigrationsHistoryTable(MigrationTableName, SchemaName));
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema(SchemaName);

        modelBuilder.Entity<PageFetchEntity>(entity =>
        {
            entity.ToTable("PageFetches");
            entity.HasKey(x => x.Id);
            entity.Property(x => x.Id).HasMaxLength(64);
            entity.Property(x => x.Url).HasMaxLength(2000).IsRequired();
            entity.Property(x => x.CallerService).HasMaxLength(64).IsRequired();
            entity.Property(x => x.Html).IsRequired();
            entity.Property(x => x.Text).IsRequired();
            entity.Property(x => x.ErrorMessage).HasMaxLength(2000);
            entity.Property(x => x.JobSearchSessionId).HasMaxLength(64);
            entity.Property(x => x.CreatedAt).HasDefaultValueSql("SYSUTCDATETIME()");

            entity.HasIndex(x => x.JobSearchSessionId);

            entity.HasIndex(x => x.Url);
            entity.HasIndex(x => x.CreatedAt);
        });
    }
}
