using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Domain.Entities.Members.Logs
{
    /// <summary>
    /// 로그인 기록
    /// </summary>
    public class MemberLoginLog
    {
        [ForeignKey(nameof(MemberID))]
        public virtual Member Member { get; private set; } = null!;

        [Key]
        public int ID { get; private set; }

        public int? MemberID { get; private set; }

        public bool Success { get; private set; } = false;

        public string Account { get; private set; } = default!;

        public string? Reason { get; private set; }

        public string? Referer { get; private set; }

        public string? Url { get; private set; }

        public string? IpAddress { get; private set; }

        public string? UserAgent { get; private set; }

        public DateTime CreatedAt { get; private set; } = DateTime.UtcNow;

        private MemberLoginLog() { }

        private MemberLoginLog(int? memberID, bool success, string account, string? reason, string? referer, string? url, string? ipAddress, string? userAgent)
        {
            if (string.IsNullOrWhiteSpace(account))
            {
                throw new ArgumentException("Account is required.", nameof(account));
            }

            if (account.Length > 120)
            {
                throw new ArgumentOutOfRangeException(nameof(account));
            }

            if (reason is not null && reason.Length > 225)
            {
                throw new ArgumentOutOfRangeException(nameof(reason));
            }

            if (url is not null && url.Length > 500)
            {
                throw new ArgumentOutOfRangeException(nameof(url));
            }

            if (ipAddress is not null && ipAddress.Length > 45)
            {
                throw new ArgumentOutOfRangeException(nameof(ipAddress));
            }

            if (userAgent is not null && userAgent.Length > 512)
            {
                throw new ArgumentOutOfRangeException(nameof(userAgent));
            }

            MemberID = memberID;
            Success = success;
            Account = account;
            Reason = reason;
            Referer = referer;
            Url = url;
            IpAddress = ipAddress;
            UserAgent = userAgent;
            CreatedAt = DateTime.UtcNow;
        }

        public static MemberLoginLog Create(int? memberID, bool success, string account, string? reason = null, string? referer = null, string? url = null, string? ipAddress = null, string? userAgent = null)
        {
            return new(memberID, success, account, reason, referer, url, ipAddress, userAgent);
        }
    }
}