using DocumentFormat.OpenXml.InkML;
using Indotalent.Data.Entities;
using Indotalent.Infrastructure.Authentication.Identity;
using Indotalent.Infrastructure.Authorization.Identity;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Infrastructure.Database.Demo;

public static class UserSeeder
{
    public static async Task GenerateDataAsync(UserManager<ApplicationUser> userManager, AppDbContext context, IConfiguration configuration, string? tenantId = null)
    {

        var adminSettings = configuration.GetSection("IdentitySettings:DefaultAdmin").Get<DefaultAdminSettings>();
        if (adminSettings == null) return;

        if (context.Users.Where(x => x.Email != adminSettings.Email).Any()) return;

        var userNames = new List<string>
        {
            "Alex", "Taylor", "Jordan", "Morgan", "Riley",
            "Casey", "Peyton", "Cameron", "Jamie", "Drew",
            "Dakota", "Avery", "Quinn", "Harper", "Rowan",
            "Emerson", "Finley", "Skyler", "Charlie", "Sage"
        };

        var defaultPassword = "123456";
        var domain = "@example.com";
        var role = ApplicationRoles.Member;

        var createdUsers = new List<ApplicationUser>();

        foreach (var name in userNames)
        {
            var email = $"{name.ToLower()}{domain}";

            var existingUser = await userManager.FindByEmailAsync(email);
            if (existingUser == null)
            {
                var applicationUser = new ApplicationUser
                {
                    UserName = email,
                    Email = email,
                    FullName = name,
                    EmailConfirmed = true
                };

                var result = await userManager.CreateAsync(applicationUser, defaultPassword);

                if (result.Succeeded)
                {
                    await userManager.AddToRoleAsync(applicationUser, role);
                    createdUsers.Add(applicationUser);
                }
            }
            else
            {
                createdUsers.Add(existingUser);
            }
        }

        // Map all users to the specified tenant
        if (!string.IsNullOrEmpty(tenantId))
        {
            foreach (var user in createdUsers)
            {
                var isMapped = await context.Set<TenantUser>()
                    .AnyAsync(tu => tu.TenantId == tenantId && tu.UserId == user.Id);

                if (!isMapped)
                {
                    var tenantUser = new TenantUser
                    {
                        TenantId = tenantId,
                        UserId = user.Id,
                        Summary = $"Demo user {user.FullName}",
                        IsActive = true
                    };

                    await context.Set<TenantUser>().AddAsync(tenantUser);
                }
            }

            await context.SaveChangesAsync();
        }
    }
}
