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

namespace Elwig.Models.Entities {
    [Table("member"), PrimaryKey("MgNr")]
    public class Member : IAddress {
        [Column("mgnr")]
        public int MgNr { get; set; }

        [Column("predecessor_mgnr")]
        public int? PredecessorMgNr { get; set; }

        [Column("prefix")]
        public string? Prefix { get; set; }

        [Column("given_name")]
        public required string GivenName { get; set; }

        [Column("middle_names")]
        public string? MiddleName { get; set; }

        [NotMapped]
        public string[] MiddleNames {
            get => (MiddleName != null) ? MiddleName.Split(" ") : [];
            set => MiddleName = (value.Length > 0) ? string.Join(" ", value) : null;
        }

        [Column("family_name")]
        public required string FamilyName { get; set; }

        [Column("suffix")]
        public string? Suffix { get; set; }

        public string Name =>
            (Prefix != null ? Prefix + " " : "") +
            GivenName + " " +
            (MiddleName != null ? MiddleName + " " : "") +
            FamilyName +
            (Suffix != null ? " " + Suffix : "");

        public string ShortName => GivenName + " " + FamilyName;

        public string AdministrativeName => AdministrativeName1 + " " + AdministrativeName2;

        public string AdministrativeName1 => FamilyName.Replace('ß', 'ẞ').ToUpper();

        public string AdministrativeName2 =>
            (Prefix != null ? Prefix + " " : "") +
            GivenName +
            (MiddleName != null ? " " + MiddleName : "") +
            (Suffix != null ? " " + Suffix : "");

        [Column("birthday")]
        public string? Birthday { get; set; }

        [Column("entry_date")]
        public string? EntryDateString { get; set; }

        [NotMapped]
        public DateOnly? EntryDate {
            get => EntryDateString != null ? DateOnly.ParseExact(EntryDateString, "yyyy-MM-dd") : null;
            set => EntryDateString = value?.ToString("yyyy-MM-dd");
        }

        [Column("exit_date")]
        public string? ExitDateString { get; set; }

        [NotMapped]
        public DateOnly? ExitDate {
            get => ExitDateString != null ? DateOnly.ParseExact(ExitDateString, "yyyy-MM-dd") : null;
            set => ExitDateString = value?.ToString("yyyy-MM-dd");
        }

        [Column("business_shares")]
        public int BusinessShares { get; set; }

        [Column("accounting_nr")]
        public string? AccountingNr { get; set; }

        [Column("zwstid")]
        public string? ZwstId { get; set; }

        [Column("lfbis_nr")]
        public string? LfbisNr { get; set; }

        [Column("ustid_nr")]
        public string? UstIdNr { get; set; }

        [Column("volllieferant")]
        public bool IsVollLieferant { get; set; }

        [Column("buchführend")]
        public bool IsBuchführend { get; set; }

        [Column("organic")]
        public bool IsOrganic { get; set; }

        [Column("funktionär")]
        public bool IsFunktionär { get; set; }

        [Column("active")]
        public bool IsActive { get; set; }

        [Column("deceased")]
        public bool IsDeceased { get; set; }

        [Column("iban")]
        public string? Iban { get; set; }

        [Column("bic")]
        public string? Bic { get; set; }

        [Column("country")]
        public int CountryNum { get; set; }

        [Column("postal_dest")]
        public string PostalDestId { get; set; } = null!;

        [Column("address")]
        public string Address { get; set; } = null!;

        [Column("default_kgnr")]
        public int? DefaultKgNr { get; set; }

        [Column("contact_postal")]
        public bool ContactViaPost { get; set; }

        [Column("contact_email")]
        public bool ContactViaEmail { get; set; }

        [Column("comment")]
        public string? Comment { get; set; }

        [ForeignKey("PredecessorMgNr")]
        public virtual Member? Predecessor { get; private set; }

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

        [ForeignKey("CountryNum, PostalDestId")]
        public virtual PostalDest PostalDest { get; private set; } = null!;

        [ForeignKey("DefaultKgNr")]
        public virtual WbKg? DefaultWbKg { get; private set; }

        [NotMapped]
        public AT_Kg? DefaultKg => DefaultWbKg?.AtKg;

        [ForeignKey("ZwstId")]
        public virtual Branch? Branch { get; private set; }

        [InverseProperty("Member")]
        public virtual ISet<AreaCom> AreaCommitments { get; private set; } = null!;

        public IEnumerable<AreaCom> ActiveAreaCommitments(AppDbContext ctx) {
            return ctx.AreaCommitments
                .Where(c => c.MgNr == MgNr && c.YearFrom <= Utils.CurrentYear && (c.YearTo ?? int.MaxValue) >= Utils.CurrentYear);
        }

        [InverseProperty("Member")]
        public virtual BillingAddr? BillingAddress { get; private set; }

        [InverseProperty("Member")]
        public virtual ISet<Delivery> Deliveries { get; private set; } = null!;

        [InverseProperty("Member")]
        public virtual ISet<MemberTelNr> TelephoneNumbers { get; private set; } = null!;

        [InverseProperty("member")]
        public virtual ISet<MemberEmailAddr> EmailAddresses { get; private set; } = null!;

        public string FullAddress => $"{Address}, {PostalDest.AtPlz?.Plz} {PostalDest.AtPlz?.Ort.Name}";

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