using Fengling.Platform.Domain.AggregatesModel.RoleAggregate;
using Fengling.Platform.Domain.AggregatesModel.TenantAggregate;
using Fengling.Platform.Domain.AggregatesModel.UserAggregate;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;

namespace Fengling.Platform.Infrastructure;

public static class SeedData
{
    
    public static async Task<Tenant> InitializeAsync(this IServiceScope scope)
    {
        var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
        var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<ApplicationRole>>();
        
        var context=  scope.ServiceProvider.GetRequiredService<PlatformDbContext>();
        await context.Database.EnsureCreatedAsync();

        var adminTenant = context.Tenants
            .FirstOrDefault(t => t.TenantCode == "Administrator");
        if (adminTenant != null)
        {
            return adminTenant;
        }

        adminTenant = new Tenant
        {
            TenantCode = "Administrator",
            Name = "超级系统",
            ContactName = "",
            ContactEmail = "",
            Status = TenantStatus.Active,
            CreatedAt = DateTime.UtcNow
        };
        await context.Tenants.AddAsync(adminTenant);
        
        
        var role = await roleManager.Roles
            .OfType<ApplicationRole>()
            .AsQueryable()
            .FirstOrDefaultAsync(x=>x.Name == "admin" && x.TenantId ==null);

        if (role == null)
        {
            role = new ApplicationRole()
            {
                CreatedTime = DateTimeOffset.UtcNow,
                TenantId = null,
                Name = "admin", Description = "系统管理员",
                DisplayName = "系统管理员",
                IsSystem = true,
            };
            await roleManager.CreateAsync(role);
        }
        
        var user = await userManager.FindByNameAsync("admin");
        if (user != null)
        {
            user = new ApplicationUser()
            {
                UserName =  "admin",
                RealName = "系统超级管理员",
                Email = "samsu9194@163.com",
                TenantInfo = new TenantInfo(adminTenant),
                PhoneNumber = "15921072307"
            };
            await userManager.AddToRoleAsync(user, "admin");
            await userManager.CreateAsync(user, "admin");
        }
        
        
        await context.SaveChangesAsync();
        return adminTenant;
    }
}