using AutoMapper;
using Common.Dtos.Prompt;
using Hushian.Application.Contracts.Persistence;
using Hushian.Application.Models;
using Hushian.Domain.Entites;
using Microsoft.EntityFrameworkCore;

namespace Hushian.Application.Services
{
	public class PromptService
	{
		private readonly IGenericRepository<Prompt> _promptRepository;
		private readonly IMapper _mapper;

		public PromptService(IGenericRepository<Prompt> promptRepository, IMapper mapper)
		{
			_promptRepository = promptRepository;
			_mapper = mapper;
		}

		public async Task<ResponseBase<bool>> AddPrompt(ADD_PromptDto model, int CompanyID)
		{
			ResponseBase<bool> response = new();
			try
			{
				var entity = _mapper.Map<Prompt>(model);
				entity.CompanyID = CompanyID;
				entity.Cdatetime = DateTime.Now;
				response.Value = response.Success = await _promptRepository.ADDBool(entity);
			}
			catch (Exception)
			{
				response.Errors.Add("خطا در ذخیره سازی");
			}
			return response;
		}

		public async Task<ReadANDUpdate_PromptDto?> GetPrompt(int id, int CompanyID)
		{
			var entity = await _promptRepository.Get().FirstOrDefaultAsync(f => f.ID == id && f.CompanyID == CompanyID);
			return _mapper.Map<ReadANDUpdate_PromptDto>(entity);
		}

		public async Task<List<ReadANDUpdate_PromptDto>> GetCompanyPrompts(int CompanyID)
		{
			var list = await _promptRepository.Get().Where(w => w.CompanyID == CompanyID).OrderByDescending(o=>o.ID).ToListAsync();
			return _mapper.Map<List<ReadANDUpdate_PromptDto>>(list);
		}

		public async Task<ResponseBase<bool>> UpdatePrompt(ReadANDUpdate_PromptDto model, int CompanyID)
		{
			ResponseBase<bool> response = new();
			try
			{
				var entity = await _promptRepository.Get().FirstOrDefaultAsync(f => f.ID == model.ID && f.CompanyID == CompanyID);
				if (entity == null)
				{
					response.Errors.Add("یافت نشد");
					return response;
				}
				entity.Test = model.Test;
				response.Value = response.Success = await _promptRepository.UPDATEBool(entity);
			}
			catch (Exception)
			{
				response.Errors.Add("خطای سیستمی");
			}
			return response;
		}

		public async Task<ResponseBase<bool>> DeletePrompt(int id, int CompanyID)
		{
			ResponseBase<bool> response = new();
			try
			{
				var entity = await _promptRepository.Get().FirstOrDefaultAsync(f => f.ID == id && f.CompanyID == CompanyID);
				if (entity == null)
				{
					response.Errors.Add("یافت نشد");
					return response;
				}
				response.Value = response.Success = await _promptRepository.DELETE(entity);
			}
			catch (Exception)
			{
				response.Errors.Add("خطای سیستمی");
			}
			return response;
		}
	}
}


