using BankContracts.BindingModels;
using BankContracts.ViewModels;
using BankDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BankDatabaseImplement.Models
{
    public class Deal : IDealModel
    {
        public int Id { get; set; }
        [Required]
        public int ClientId { get; set; }
        [Required]
        public DateTime DealDate { get; set; } = DateTime.Now;
        [Required]
        public int OperatorId { get; set; }
        public virtual Operator Operator { get; set; } = new();
        public int? CreditProgramId {get; set; }
        public virtual CreditProgram CreditProgram { get; set; } = new();
        [ForeignKey("DealId")]
        public virtual List<DealPayment> DealPayments { get; set; } = new();
        public static Deal? Create(BankDatabase context, DealBindingModel model)
        {
            if (model == null)
            {
                return null;
            }
            return new Deal()
            {
                Id = model.Id,
                ClientId = model.ClientId,
                DealDate = model.DealDate,
                OperatorId = model.OperatorId,
                Operator = context.Operators.First(x => x.Id == model.OperatorId)
            };
        }
        public static Deal? Create(BankDatabase context, DealViewModel model)
        {
            return new Deal()
            {
                Id = model.Id,
                ClientId = model.ClientId,
                DealDate = model.DealDate,
                OperatorId = model.OperatorId,
                Operator = context.Operators.First(x => x.Id == model.OperatorId)
            };
        }
        public void Update(DealBindingModel? model)
        {
            if (model == null)
            {
                return;
            }
            ClientId = model.ClientId;
            if (model.CreditProgramId.HasValue) CreditProgramId = CreditProgramId;
        }
        public DealViewModel GetViewModel => new()
        {
            Id = Id,
            ClientId = ClientId,
            CreditProgramId = CreditProgramId,
            DealDate = DealDate,
            OperatorId = OperatorId,
            OperatorName = Operator.LastName + " " + Operator.FirstName + " " + Operator.MiddleName,
        };
    }
}
