using Berufsschule_HAM.Services;
using Microsoft.AspNetCore.Mvc;
using Novell.Directory.Ldap;
using Berufsschule_HAM.Models;
using System.Text.Json;
using Microsoft.AspNetCore.Authorization;

[Authorize]
[Route("[controller]")]
public class GroupsController : Controller
{
    private readonly LdapService _ldap;
    private readonly ILogger<UsersController> _logger;

    public GroupsController(LdapService ldap, ILogger<UsersController> logger)
    {
        _ldap = ldap;
        _logger = logger;
    }

    [HttpGet("Index")]
    public async Task<IEnumerable<GroupModel>> Index(GroupsIndexRequestModel requestModel)
    {
        string? cn = requestModel.Cn;
        List<string> attributes = [.. _ldap.GroupsAttributes];
        if (!requestModel.GidNumber) attributes.Remove("gidNumber");
        if (!requestModel.Permissions) attributes.Remove("description");
        IEnumerable<GroupModel> groups;
        if (cn is null)
        {
            groups = await _ldap.ListGroupsAsync([.. attributes]);
        }
        else
        {
            try
            {
                groups = [await _ldap.GetGroupByCnAsync(cn, [.. attributes])];
            }
            catch (InvalidOperationException)
            {
                groups = [];
            }
        }
        return groups;
    }

    [HttpGet("Delete")]
    public async Task<bool> Delete(string uid)
    {
        return await Task.Run(async () =>
        {
            try
            {
                await _ldap.DeleteGroupAsync(uid);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        });
    }

    [HttpGet("Create")]
    public async Task<bool> Create(string cn, string gidNumber, GroupPermission[] permissions, string description)
    {
        try
        {
            description ??= JsonSerializer.Serialize(new GroupPermissions() {Permissions = []});

            LdapAttributeSet attributeSet =
            [
                new LdapAttribute("objectClass", "posixGroup"),
                new LdapAttribute("objectClass", "top"),
                new LdapAttribute("cn", cn),
                new LdapAttribute("gidNumber", gidNumber),
                new LdapAttribute(
                    "description",
                    JsonSerializer.Serialize(new GroupPermissions()
                    {
                        Permissions = [.. permissions]
                    }))
            ];
            
            await _ldap.CreateGroup(cn, attributeSet);
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError("Unable to create user: {ex.Message} - {ex.StackTrace}", [ex.Message, ex.StackTrace]);
            return false;
        }
    }
    
    [HttpPost("Update")]
    public async Task<bool> Update([FromBody]GroupsModifyRequestModel requestModel)
    {
        if (requestModel is null)
        {
            _logger.LogError("Unable to update a group because the GroupsModifyRequestModel is null");
            return false;
        }
        string cn = requestModel.Cn;

        if (requestModel.NewCn is not null)
        {
            await _ldap.UpdateGroup(cn, "cn", requestModel.NewCn);
            cn = requestModel.NewCn;
        }
        if (requestModel.GidNumber is not null)
        {
            await _ldap.UpdateGroup(cn, "gidNumber", requestModel.GidNumber);
        }
        if (requestModel.Permissions is not null)
        {
            await _ldap.UpdateGroup(cn, "description", JsonSerializer.Serialize(requestModel.Permissions));
        }
        return true;
    }
}