using Elwig.Helpers;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;

namespace Elwig.Models.Entities {
    [Table("delivery_announcement"), PrimaryKey("Year", "DsNr", "MgNr", "SortId")]
    public class DeliveryAncmt {

        [Column("year")]
        public int Year { get; set; }

        [Column("dsnr")]
        public int DsNr { get; set; }

        [Column("mgnr")]
        public int MgNr { get; set; }

        [Column("sortid")]
        public required string SortId { get; set; }

        [Column("weight")]
        public int Weight { get; set; }

        [Column("type")]
        public required string Type { get; set; }

        [Column("ctime"), DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        public long CTime { get; set; }
        [NotMapped]
        public DateTime CreatedAt {
            get => DateTimeOffset.FromUnixTimeSeconds(CTime).LocalDateTime;
            set => CTime = ((DateTimeOffset)value.ToUniversalTime()).ToUnixTimeSeconds();
        }

        [Column("mtime"), DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        public long MTime { get; set; }
        [NotMapped]
        public DateTime ModifiedAt {
            get => DateTimeOffset.FromUnixTimeSeconds(MTime).LocalDateTime;
            set => MTime = ((DateTimeOffset)value.ToUniversalTime()).ToUnixTimeSeconds();
        }

        [Column("xtime")]
        public long? XTime { get; set; }
        [NotMapped]
        public DateTime? ExportedAt {
            get => XTime == null ? null : DateTimeOffset.FromUnixTimeSeconds(XTime.Value).LocalDateTime;
            set => XTime = value == null ? null : ((DateTimeOffset)value.Value.ToUniversalTime()).ToUnixTimeSeconds();
        }

        [Column("itime")]
        public long? ITime { get; set; }
        [NotMapped]
        public DateTime? ImportedAt {
            get => ITime == null ? null : DateTimeOffset.FromUnixTimeSeconds(ITime.Value).LocalDateTime;
            set => ITime = value == null ? null : ((DateTimeOffset)value.Value.ToUniversalTime()).ToUnixTimeSeconds();
        }

        [ForeignKey("Year, DsNr")]
        public virtual DeliverySchedule Schedule { get; private set; } = null!;

        [ForeignKey("MgNr")]
        public virtual Member Member { get; private set; } = null!;

        [ForeignKey("SortId")]
        public virtual WineVar Variety { get; private set; } = null!;

        public int SearchScore(IEnumerable<string> keywords) {
            return Utils.GetSearchScore([
                Schedule.Description,
                Member.Name, Member.MiddleName, Member.GivenName,
                Member.BillingAddress?.FullName,
            ], keywords);
        }
    }
}
