using Contracts.BindingModels;
using Contracts.SearchModels;
using Contracts.StoragesContracts;
using Contracts.ViewModels;
using DatabaseImplement.Models;

namespace DatabaseImplement.Implements
{
	public class WorkerStorage : IWorkerStorage
	{
		public WorkerViewModel? Delete(WorkerBindingModel model)
		{
			using var context = new FactoryGoWorkDatabase();
			var newWorker = context.Workers.FirstOrDefault(x => x.Id == model.Id);
			if (newWorker == null)
				return null;
			context.Workers.Remove(newWorker);
			context.SaveChanges();
			return newWorker.GetViewModel;
		}

		public WorkerViewModel? GetElement(WorkerSearchModel model)
		{
			using var context = new FactoryGoWorkDatabase();
			return context.Workers.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Equals(model.Name)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
		}

		public List<WorkerViewModel> GetFilteredList(WorkerSearchModel model)
		{
            if (!model.UserId.HasValue)
            {
                return new();
            }
            using var context = new FactoryGoWorkDatabase();
            return context.Workers.Where(x => x.UserId == model.UserId).Select(x => x.GetViewModel).ToList();
        }

		public List<WorkerViewModel> GetFullList()
		{
			using var context = new FactoryGoWorkDatabase();
			return context.Workers.Select(x => x.GetViewModel).ToList();
		}

		public WorkerViewModel? Insert(WorkerBindingModel model)
		{
			using var context = new FactoryGoWorkDatabase();
			var newWorker = Worker.Create(model);
			if (newWorker == null)
				return null;
			context.Workers.Add(newWorker);
			context.SaveChanges();
			return newWorker.GetViewModel;
		}

		public WorkerViewModel? Update(WorkerBindingModel model)
		{
			using var context = new FactoryGoWorkDatabase();
			var newWorker = context.Workers.FirstOrDefault(x => x.Id == model.Id);
			if (newWorker == null)
				return null;
			newWorker.Update(model);
			context.SaveChanges();
			return newWorker.GetViewModel;
		}
	}
}
