using FoodsharingSiegen.Contracts;
using FoodsharingSiegen.Contracts.Entity;
using FoodsharingSiegen.Contracts.Model;
using FoodsharingSiegen.Server.Auth;
using Microsoft.EntityFrameworkCore;

namespace FoodsharingSiegen.Server.Data.Service
{
    /// <summary>
    /// The prospect service class (a. beging, 01.04.2022)
    /// </summary>
    /// <seealso cref="ServiceBase"/>
    public class ProspectService : ServiceBase
    {
        private AuditService AuditService { get; }

        #region Setup/Teardown

        /// <summary>
        /// Initializes a new instance of the <see cref="ProspectService"/> class
        /// </summary>
        /// <param name="context">The context</param>
        /// <param name="authService"></param>
        /// <param name="auditService"></param>
        public ProspectService(FsContext context, AuthService authService, AuditService auditService) : base(context, authService) => AuditService = auditService;

        #endregion

        #region Public Method AddInteraction

        /// <summary>
        /// Adds the interaction using the specified interaction (a. beging, 02.04.2022)
        /// </summary>
        /// <param name="interaction">The interaction</param>
        /// <returns>A task containing an operation result of interaction</returns>
        public async Task<OperationResult<Interaction>> AddInteraction(Interaction interaction)
        {
            try
            {
                var targetProspect = await Context.Prospects!.Include(x => x.Interactions).FirstOrDefaultAsync(x => x.Id == interaction.ProspectID);
                if (targetProspect == null) return new OperationResult<Interaction>(new Exception("Invalid prospect id"));
                
                interaction.ProspectID = Guid.Empty;
                interaction.Created = DateTime.UtcNow;

                targetProspect.Interactions.Add(interaction);
                
                await Context.SaveChangesAsync();
                
                await AuditService.Insert(AuditType.AddInteraction, targetProspect.Name, interaction.Type.ToString());
                
                // Detatch entities
                Context.Entry(targetProspect).State = EntityState.Detached;
                Context.Entry(interaction).State = EntityState.Detached;
                
                return new OperationResult<Interaction>(interaction);
            }
            catch (Exception e)
            {
                return new OperationResult<Interaction>(e);
            }
        }

        #endregion

        #region Public Method AddProspectAsync

        /// <summary>
        /// Adds the prospect using the specified prospect (a. beging, 01.04.2022)
        /// </summary>
        /// <param name="prospect">The prospect</param>
        /// <returns>A task containing an operation result of prospect</returns>
        public async Task<OperationResult<Prospect>> AddProspectAsync(Prospect? prospect)
        {
            try
            {
                if (prospect == null) return new OperationResult<Prospect>(new Exception("Cannot be empty"));

                prospect.Created = DateTime.UtcNow;
                prospect.Id = Guid.Empty;

                await Context.Prospects!.AddAsync(prospect);
                var saveR = await Context.SaveChangesAsync();

                if (saveR > 0)
                {
                    await AuditService.Insert(AuditType.CreateProspect, prospect.Name, prospect.FsId.ToString());
                    return new OperationResult<Prospect>(prospect);
                }
            
                return new OperationResult<Prospect>(new Exception("Couldn't add prospect"));
            }
            catch (Exception e)
            {
                return new OperationResult<Prospect>(e);
            }
        }

        #endregion

        #region Public Method GetProspectsAsync

        /// <summary>
        /// Gets the users (a. beging, 01.04.2022)
        /// </summary>
        /// <returns>A task containing an operation result of list prospect</returns>
        public async Task<OperationResult<List<Prospect>>> GetProspectsAsync(GetProspectsParameter parameter)
        {
            try
            {
                var prospectsQuery = Context.Prospects!.AsNoTracking().Include(x => x.Interactions.OrderBy(i => i.Date)).ThenInclude(x => x.User).OrderBy(x => x.Name).AsQueryable();
                
                if(parameter.MustHaveInteractions != null && parameter.MustHaveInteractions.Any()) 
                    prospectsQuery = prospectsQuery.Where(x => x.Interactions.Any(i => parameter.MustHaveInteractions.Contains(i.Type)));
                
                if(parameter.CannotHaveInteractions != null && parameter.CannotHaveInteractions.Any())
                    prospectsQuery = prospectsQuery.Where(x => x.Interactions.All(i => !parameter.CannotHaveInteractions.Contains(i.Type)));
                
                var prospects = await prospectsQuery.ToListAsync();
                
                return new OperationResult<List<Prospect>>(prospects);
            }
            catch (Exception e)
            {
                return new OperationResult<List<Prospect>>(e);
            }
        }

        #endregion

        #region Public Method RemoveInteraction

        /// <summary>
        /// Removes the interaction using the specified interaction id (a. beging, 11.04.2022)
        /// </summary>
        /// <param name="interactionId">The interaction id</param>
        /// <returns>A task containing the operation result</returns>
        public async Task<OperationResult> RemoveInteraction(Guid interactionId)
        {
            try
            {
                Context.Interactions!.Remove(new Interaction { Id = interactionId });
                await Context.SaveChangesAsync();

                await AuditService.Insert(AuditType.RemoveInteraction, "?");
                
                return new OperationResult();
            }
            catch (Exception e)
            {
                return new OperationResult(e);
            }
        }

        #endregion

        #region Public Method UpdateAsync

        /// <summary>
        /// Updates the prospect (a. beging, 11.04.2022)
        /// </summary>
        /// <param name="prospect">The prospect</param>
        /// <returns>A task containing the operation result</returns>
        public async Task<OperationResult> UpdateAsync(Prospect prospect)
        {
            try
            {
                var entityProspect = await Context.Prospects!.FirstOrDefaultAsync(x => x.Id == prospect.Id);
                if (entityProspect == null) return new OperationResult(new Exception("Prospect not found"));

                entityProspect.Memo = prospect.Memo;
                entityProspect.Name = prospect.Name;
                entityProspect.FsId = prospect.FsId;
                entityProspect.Warning = prospect.Warning;
            
                var saveR = await Context.SaveChangesAsync();
            
                if(saveR < 1) return new OperationResult(new Exception("Fehler beim speichern"));
                
                await AuditService.Insert(AuditType.EditProspect, prospect.Name);
                return new OperationResult();
            }
            catch (Exception e)
            {
                return new OperationResult(e);
            }
        }

        #endregion
    }
}