using Microsoft.AspNetCore.Http;
using System.Collections;
using System.ComponentModel.DataAnnotations;

namespace SharedKernel.Attributes
{
    /*
     * 파일 확장자 제한
     */
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class AllowedExtensionsAttribute : ValidationAttribute
    {
        private readonly string[] _extensions;

        public AllowedExtensionsAttribute(string extensions)
        {
            _extensions = extensions.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(x => x.Trim().TrimStart('.').ToLowerInvariant()).Where(x => x.Length > 0).ToArray();
        }

        public override bool IsValid(object? value)
        {
            if (value is IFormFile file)
            {
                return _checkExtension(file.FileName);
            }

            if (value is IEnumerable files)
            {
                foreach (var obj in files)
                {
                    if (obj is IFormFile f && !_checkExtension(f.FileName))
                    {
                        return false;
                    }
                }
            }

            return true;
        }

        public override string FormatErrorMessage(string name)
        {
            var template = string.IsNullOrWhiteSpace(ErrorMessage) ? "{0}에 허용되지 않은 파일 형식이 있습니다.\n\n허용 확장자: [{1}]" : ErrorMessage;

            return string.Format(template, name, string.Join(", ", _extensions));
        }

        private bool _checkExtension(string fileName)
        {
            var ext = Path.GetExtension(fileName)?.TrimStart('.').ToLowerInvariant();

            return !string.IsNullOrEmpty(ext) && _extensions.Contains(ext);
        }
    }
}