using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MarcusLaw.OutlookAddin.Core.Models;

namespace MarcusLaw.OutlookAddin.Core.Services
{
    public interface IAttachmentSaveService
    {
        /// <summary>
        /// Uploads each attachment as an EspoCRM Attachment, then asks
        /// Marcus-Law's NetworkStorage integration to place the file under
        /// <paramref name="targetFolderPath"/> on the shared storage. No
        /// Document entity is created — these are raw files dropped into
        /// the case's filesystem folder.
        /// </summary>
        /// <param name="attachments">files to save</param>
        /// <param name="targetFolderPath">
        /// Full relative folder path on storage, e.g.
        /// <c>"30-מרדכי שמביקו/אסמכתאות"</c>. The case folder + optional
        /// subfolder. Filename is appended internally.
        /// </param>
        Task<AttachmentSaveSummary> SaveAsync(
            IReadOnlyList<EspoAttachment> attachments,
            string targetFolderPath,
            CancellationToken cancellationToken = default);
    }

    public sealed class AttachmentSaveSummary
    {
        public List<AttachmentSaveItemResult> Items { get; set; } = new List<AttachmentSaveItemResult>();

        public bool AuthRequired { get; set; }

        public int SavedCount
        {
            get
            {
                var n = 0;
                foreach (var it in Items)
                {
                    if (it.Outcome == AttachmentSaveOutcome.Saved) n++;
                }
                return n;
            }
        }

        public int FailedCount
        {
            get
            {
                var n = 0;
                foreach (var it in Items)
                {
                    if (it.Outcome == AttachmentSaveOutcome.Failed) n++;
                }
                return n;
            }
        }
    }

    public sealed class AttachmentSaveItemResult
    {
        public string FileName { get; set; } = string.Empty;

        public AttachmentSaveOutcome Outcome { get; set; }

        public string? AttachmentId { get; set; }

        public string? ErrorMessage { get; set; }
    }

    public enum AttachmentSaveOutcome
    {
        Saved,
        Failed,
        AuthRequired
    }
}
