using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Migrations.Internal;
using Microsoft.Extensions.Configuration;
using OpenIddict.EntityFrameworkCore.Models;

namespace Ablera.Serdica.DBModels.Oidc;

 public class OidcDbContext : DbContext
{
    public OidcDbContext(DbContextOptions<OidcDbContext> options)
        : base(options)
    {
    }

    public virtual DbSet<OpenIddictEntityFrameworkCoreApplication> OpenIddictApplications { get; set; }
    public virtual DbSet<OpenIddictEntityFrameworkCoreAuthorization> OpenIddictAuthorizations { get; set; }
    public virtual DbSet<OpenIddictEntityFrameworkCoreScope> OpenIddictScopes { get; set; }
    public virtual DbSet<OpenIddictEntityFrameworkCoreToken> OpenIddictTokens { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.HasAnnotation("Relational:DefaultStringType", "NVARCHAR2(4000)");
        base.OnModelCreating(builder);

        builder.UseOpenIddict();

        // Configure the OpenIddict Applications table.
        builder.Entity<OpenIddictEntityFrameworkCoreApplication>(entity =>
        {
            // Map to table with prefix "OIDC_" in the "SRD_SYS" schema.
            entity.ToTable("OIDC_APPLICATIONS", "SRD_SYS");

            // Ensure that ClientId is unique.
            entity.HasIndex(e => e.ClientId)
                  .IsUnique();

            // Optionally configure column size for ClientSecret (Oracle commonly uses VARCHAR2).
            entity.Property(e => e.ClientSecret)
                  .HasMaxLength(256);

            // Additional tuning: you might also constrain DisplayName or ConsentType here.
        });

        // Configure the OpenIddict Authorizations table.
        builder.Entity<OpenIddictEntityFrameworkCoreAuthorization>(entity =>
        {
            entity.ToTable("OIDC_AUTHORIZATIONS", "SRD_SYS");
        });

        // Configure the OpenIddict Scopes table.
        builder.Entity<OpenIddictEntityFrameworkCoreScope>(entity =>
        {
            entity.ToTable("OIDC_SCOPES", "SRD_SYS");

            // Typically, scopes have a unique name.
            entity.HasIndex(e => e.Name)
                  .IsUnique();
        });

        // Configure the OpenIddict Tokens table.
        builder.Entity<OpenIddictEntityFrameworkCoreToken>(entity =>
        {
            entity.ToTable("OIDC_TOKENS", "SRD_SYS");

            // Create an index on ReferenceId for quick lookups.
            entity.HasIndex(e => e.ReferenceId)
                  .IsUnique();

            // Optionally, you can configure the max length for certain token fields.
            // For example, if ReferenceId should be a VARCHAR2(100):
            entity.Property(e => e.ReferenceId)
                  .HasMaxLength(100);
        });
    }
}