using System.Text.Json;
using Berufsschule_HAM.Models;
using Berufsschule_HAM.Services;

namespace Berufsschule_HAM.Helpers;
public static class SynchronizationHelper
{
    public static async Task SyncAssetOwnership(LdapService ldap, string oldName, string newName)
    {
        bool remove = string.IsNullOrEmpty(newName);
        string uidString = $"uid={newName}";
        IEnumerable<AssetModel> assets = [.. (await ldap.ListDeviceAsync()).Where(asset => asset.Owner == $"uid={oldName}")];
        foreach (AssetModel asset in assets)
        {
            if (remove)
            {
                await ldap.DeleteAttribute(ldap.AssetsBaseDn, "cn", asset.Cn, "owner");
            }
            else
            {
                await ldap.UpdateAsset(asset.Cn, "owner", uidString);            
            }
        };
    }

    public static async Task SyncLocationName(LdapService ldap, string oldLocation, string newLocation)
    {
        bool remove = string.IsNullOrEmpty(newLocation);
        // Update asset locations
        IEnumerable<AssetModel> assets = [.. (await ldap.ListDeviceAsync()).Where(asset => asset.Location == oldLocation)];
        foreach (AssetModel asset in assets)
        {
            if (remove)
            {
                await ldap.DeleteAttribute(ldap.AssetsBaseDn, "cn", asset.Cn, "l");
            }
            else
            {
                await ldap.UpdateAsset(asset.Cn, "l", newLocation);            
            }
        };
        
        // Update user workplace locations
        string newUserLocation = remove ? "" : newLocation;
        IEnumerable<UserModel> users = [.. (await ldap.ListUsersAsync()).Where(user => user.Description is not null && user.Description.Workplace == oldLocation)];
        foreach (UserModel user in users)
        {
            if (user.Description is null) return;
            user.Description.Workplace = newUserLocation;
            await ldap.UpdateUser(user.Uid, "description", JsonSerializer.Serialize(user.Description));
        };
    }
}