// IdentityService.cs - Tạo dịch vụ này để tránh lỗi DbContext

using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using RobotNet.IdentityServer.Data;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace RobotNet.IdentityServer.Services;
public class IdentityService
{
    private readonly IServiceProvider _serviceProvider;

    public IdentityService(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public async Task<ApplicationUser?> GetUserByIdAsync(string userId)
    {
        using var scope = _serviceProvider.CreateScope();
        var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();

        var user = await userManager.Users.AsNoTracking().FirstOrDefaultAsync(u => u.Id == userId);
        return user;
    }

    public async Task<ApplicationUser?> GetUserByNameAsync(string userName)
    {
        using var scope = _serviceProvider.CreateScope();
        var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
        return await userManager.FindByNameAsync(userName);
    }

    public async Task<List<string>> GetUserRolesAsync(ApplicationUser user)
    {
        using var scope = _serviceProvider.CreateScope();
        var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
        var roles = await userManager.GetRolesAsync(user);
        return roles.ToList();
    }

    public async Task<IdentityResult> UpdateUserAsync(ApplicationUser user)
    {
        using var scope = _serviceProvider.CreateScope();
        var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();

       
        var existingUser = await userManager.FindByIdAsync(user.Id);
        if (existingUser != null)
        {
            var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            context.Entry(existingUser).State = EntityState.Detached;
        }

        return await userManager.UpdateAsync(user);
    }

    public async Task<IdentityResult> ChangePasswordAsync(ApplicationUser user, string currentPassword, string newPassword)
    {
        using var scope = _serviceProvider.CreateScope();
        var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
        return await userManager.ChangePasswordAsync(user, currentPassword, newPassword);
    }
}


