using InABox.API;
using InABox.Core;
using InABox.Database;
using Microsoft.Exchange.WebServices.Data;

namespace InABox.Rpc
{
    
    public class RpcDeleteHandler : RpcCommandHandler<IRpcServer, RpcDeleteCommand, RpcDeleteParameters, RpcDeleteResult>
    {
        public RpcDeleteHandler(IRpcServer sender) : base(sender)
        {
        }

        protected override RpcDeleteResult Execute(IRpcSession session, RpcDeleteParameters parameters, Logger logger)
        {
            var user = CredentialsCache.ValidateAndRefresh(session.ID)
                ?? throw new RpcException("User not found in Credentials Cache!", RpcError.UNAUTHENTICATED);

            var store = DbFactory.FindStore(parameters.Type, user.ID, user.UserID, session.Platform, session.Version ?? "", logger);
                
            var items = new List<Entity>();
            foreach (var id in parameters.IDs)
            {
                var item = (Activator.CreateInstance(parameters.Type) as Entity)!;
                item.ID = id;
                item.CommitChanges();
                items.Add(item);
            }
            store.Delete(items, parameters.AuditNote);
            
            InABox.API.CredentialsCache.Refresh(parameters.Type == typeof(InABox.Core.User));

            return new RpcDeleteResult();
        }
    }
}