using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using OTSSignsOrchestrator.Core.Models.Entities;

namespace OTSSignsOrchestrator.Core.Data;

public class XiboContext : DbContext
{
    private readonly IDataProtectionProvider? _dataProtection;

    public XiboContext(DbContextOptions<XiboContext> options, IDataProtectionProvider? dataProtection = null)
        : base(options)
    {
        _dataProtection = dataProtection;
    }

    public DbSet<SshHost> SshHosts => Set<SshHost>();
    public DbSet<OperationLog> OperationLogs => Set<OperationLog>();

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

        // --- SshHost ---
        modelBuilder.Entity<SshHost>(entity =>
        {
            entity.HasIndex(e => e.Label).IsUnique();

            if (_dataProtection != null)
            {
                var protector = _dataProtection.CreateProtector("OTSSignsOrchestrator.SshHost");
                var passphraseConverter = new ValueConverter<string?, string?>(
                    v => v != null ? protector.Protect(v) : null,
                    v => v != null ? protector.Unprotect(v) : null);
                var passwordConverter = new ValueConverter<string?, string?>(
                    v => v != null ? protector.Protect(v) : null,
                    v => v != null ? protector.Unprotect(v) : null);

                entity.Property(e => e.KeyPassphrase).HasConversion(passphraseConverter);
                entity.Property(e => e.Password).HasConversion(passwordConverter);
            }
        });

        // --- OperationLog ---
        modelBuilder.Entity<OperationLog>(entity =>
        {
            entity.HasIndex(e => e.Timestamp);
            entity.HasIndex(e => e.StackName);
            entity.HasIndex(e => e.Operation);
        });
    }
}
