using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System.Net.Http.Json;
using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.MAUI.DataLayer;
using WorkFlowCheck.MAUI.Services.Interfaces;

namespace WorkFlowCheck.MAUI.Services
{
    public class CheckListService : BaseService, ICheckListService
    {
        private readonly IUserService _userService;
        public CheckListService(HttpClient httpClient, IConfiguration configuration, AppDbContext dbContext, IMapper mapper, IUserService userService) : base(httpClient, configuration, dbContext, mapper)
        {
            _userService = userService;
        }

        public async Task<ApiResponseDTO<CheckPointDTO>> GetCheckPoint(int checkPointId)
        {
            var retVal = new ApiResponseDTO<CheckPointDTO>() { IsSuccess = true };
            try
            {
                var res = await _dbContext.CheckPoints.Include(i => i.CheckListTemplateRows).Where(w => w.Id == checkPointId).FirstOrDefaultAsync();
                retVal.Data = _mapper.Map<CheckPointDTO>(res);
            }
            catch (Exception ex)
            {
                retVal.IsSuccess = false;
                retVal.Errors.Add(ex.Message);
            }
            return retVal;
        }

        public async Task<ApiResponseDTO<CheckListHeaderDTO>> StartNew(CheckListTemplateHeaderDTO checkListTemplateHeaderDTO)
        {
            try
            {
                await PrepareAuthenticatedRequestAsync();
                // Az API végpont meghatározása
                string endpoint = $"{_httpClient.BaseAddress}api/checklist/startnew";

                // HTTP POST kérés küldése
                ApiRequestDTO<CheckListTemplateHeaderDTO> request = new ApiRequestDTO<CheckListTemplateHeaderDTO>();
                request.UserDTO = _userService.GetCurrentUser();
                request.Data = checkListTemplateHeaderDTO;


                using (HttpResponseMessage httpResponseMessage = await _httpClient.PostAsJsonAsync(endpoint, request))
                {
                    httpResponseMessage.EnsureSuccessStatusCode();

                    var jsonString = await httpResponseMessage.Content.ReadAsStringAsync();
                    var response = JsonConvert.DeserializeObject<ApiResponseDTO<CheckListHeaderDTO>>(jsonString);

                    return response ?? new ApiResponseDTO<CheckListHeaderDTO>
                    {
                        IsSuccess = false,
                    };
                }
            }
            catch (Exception ex)
            {
                // Hiba visszaadása
                return new ApiResponseDTO<CheckListHeaderDTO>
                {
                    IsSuccess = false
                };
            }
        }
    }
}
