/*
 * File: ShadowedRealms.Admin/Data/ApplicationDbContext.cs
 * Created: 2025-11-01
 * Last Modified: 2025-11-01
 * Description: ApplicationDbContext configured to use existing custom Identity table names
 * Last Edit Notes: Updated to match GameDbContext table naming convention
 */

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace ShadowedRealms.Admin.Data
{
    // Custom ApplicationUser to match your exact Players_Auth table structure
    public class ApplicationUser : IdentityUser<int>
    {
        // Additional columns that exist in your Players_Auth table
        public int? PlayerId { get; set; }
        public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
        public DateTime LastLoginAt { get; set; } = DateTime.UtcNow;  // Fixed: was LastLogInAt

        // Note: All other Identity properties are inherited from IdentityUser<int>
        // and already match the table structure
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole<int>, int>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

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

            // Configure Identity tables to match existing custom table names and integer keys
            ConfigureIdentityTables(modelBuilder);
        }

        private void ConfigureIdentityTables(ModelBuilder modelBuilder)
        {
            // Match the exact table names and column structure from your database
            modelBuilder.Entity<ApplicationUser>(entity =>
            {
                entity.ToTable("Players_Auth");

                // Configure the additional columns that exist in your Players_Auth table
                entity.Property(u => u.CreatedAt)
                    .IsRequired()
                    .HasDefaultValueSql("CURRENT_TIMESTAMP");

                entity.Property(u => u.LastLoginAt)  // Fixed: was LastLogInAt
                    .IsRequired()
                    .HasDefaultValueSql("CURRENT_TIMESTAMP");

                entity.Property(u => u.PlayerId)
                    .IsRequired(false);  // Nullable in your table
            });

            modelBuilder.Entity<IdentityRole<int>>().ToTable("Roles");
            modelBuilder.Entity<IdentityUserRole<int>>().ToTable("Player_Roles");
            modelBuilder.Entity<IdentityUserClaim<int>>().ToTable("Player_Claims");
            modelBuilder.Entity<IdentityUserLogin<int>>().ToTable("Player_Logins");
            modelBuilder.Entity<IdentityRoleClaim<int>>().ToTable("Role_Claims");
            modelBuilder.Entity<IdentityUserToken<int>>().ToTable("Player_Tokens");
        }
    }
}