using DataBase.Entities.Models;
using Microsoft.Graph.SecurityNamespace;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using User.Insight.Tracker.Common;
using User.Insight.Tracker.DataContracts;
using User.Insight.Tracker.DataContracts.Requests;
using User.Insight.Tracker.DataContracts.Response;
using User.Insight.Tracker.DataProviders;
using static User.Insight.Tracker.Services.AzureSyncingService;

namespace User.Insight.Tracker.Services
{
    [ExcludeFromCodeCoverage]
    public class CommonService : ICommonService
    {
        private readonly ICommonServiceProvider _commonServiceProvider;
        private readonly IUtils _utils;
        private readonly HttpClient _httpClient;
        private readonly ILogger<CommonService> _logger;
        public CommonService(ICommonServiceProvider commonServiceProvider, IUtils utils, HttpClient httpClient, ILogger<CommonService> logger)
        {
            _commonServiceProvider = commonServiceProvider;
            _utils = utils;
            _httpClient = httpClient;
            _logger = logger;
        }

        [ExcludeFromCodeCoverage]
        public PageResponse<AuditResponse> GetAudit(SearchRequest<AuditRequest> filters, JwtTokenDetail userDetails)
        {
            if (userDetails == null)
                throw new UnauthorisedException(_utils.GetMessage("UserInvalid"));
            PageResponse<AuditResponse> data = new PageResponse<AuditResponse>();
            var response = _commonServiceProvider.GetAudit(filters, userDetails);
            var firstRecord = response.FirstOrDefault();
            if (firstRecord != null)
            {
                int totalRecords = Convert.ToInt32(firstRecord.total_records);
                int total_Pages = Convert.ToInt32(firstRecord.total_pages);
                var listResponse = response.Select(e => new AuditResponse()
                {
                    Id = e.Id,
                    table_name = e.table_name,
                    operation_type = e.operation_type,
                    old_data = e.old_data,
                    new_data = e.new_data,
                    changed_by = e.changed_by,
                    updated_on = e.updated_on,
                    UserName = e.user_id

                }).ToList();

                data.Records = listResponse;
                data.TotalRecords = totalRecords;
                data.TotalPages = total_Pages;
                data.PageSize = filters.PageSize;
                data.CurrentPage = filters.PageNumber;

            }

            return data;
        }


        [ExcludeFromCodeCoverage]
        public PageResponse<DeleteRoleResponse> DeleteRoles(SearchRequest<DeleteRoleRequest> filters, JwtTokenDetail userDetails)
        {
            if (userDetails == null)
                throw new UnauthorisedException(_utils.GetMessage("UserInvalid"));
            PageResponse<DeleteRoleResponse> data = new PageResponse<DeleteRoleResponse>();
            var response = _commonServiceProvider.DeleteRoles(filters, userDetails);
            if (response != null)
            {
                int totalRecords = response.Count;

                var listResponse = response.Select(e => new DeleteRoleResponse()
                {
                    Message = e.message,

                }).ToList();

                data.Records = listResponse;
                data.CurrentPage = 1; // Set to current page if pagination is needed
                data.PageSize = 1; // Set appropriate page size
                data.TotalRecords = 1;
                data.TotalPages = 1; // Fix: Use the correct variable

            }

            return data;
        }


        [ExcludeFromCodeCoverage]
        public List<SmartSearchResponse> GetSmartSearch(JwtTokenDetail userDetails , string EmpCode)
        {

            if (userDetails == null)
                throw new UnauthorisedException(_utils.GetMessage("UserInvalid"));
            List<SmartSearchResponse> data = new List<SmartSearchResponse>();
            var response = _commonServiceProvider.GetSmartSearch(userDetails , EmpCode);
            var firstRecord = response.ToList();
            if (firstRecord != null)
            {
                data = response.Select(e => new SmartSearchResponse()
                {
                    EmpCode = e.EmpCode,
                    EmpName = e.EmployeeName,

                }).ToList();

            }
            return data;
        }


        [ExcludeFromCodeCoverage]
        public PageResponse<GlobalConfigurationResponse> GetGlobalConfiguration(SearchRequest<GlobalConfigurationRequest> filters, JwtTokenDetail userDetails)
        {
            if (userDetails == null)
                throw new UnauthorisedException(_utils.GetMessage("UserInvalid"));
            PageResponse<GlobalConfigurationResponse> data = new PageResponse<GlobalConfigurationResponse>();
            var response = _commonServiceProvider.GetGlobalConfiguration(filters, userDetails);
            var firstRecord = response.FirstOrDefault();
            if (firstRecord != null)
            {
                int totalRecords = Convert.ToInt32(firstRecord.TotalRecords);
                int total_Pages = Convert.ToInt32(firstRecord.TotalPages);

                var listResponse = response.Select(e => new GlobalConfigurationResponse()
                {
                    Id = e.Id,
                    ProKey = e.ProKey,
                    ProValue = e.ProValue,
                    Label = e.Label,
                    Type = e.Type,
                    Placeholder = e.Placeholder,
                    Active = e.Active,
                    Editable = e.Editable,
                    Pattern = e.Pattern,
                    Min = e.Min,
                    Max = e.Max,
                    Options = e.Options,
                    HelpText = e.HelpText,
                    DefaultValue = e.DefaultValue,
                    FieldOrder = e.FieldOrder,
                    Visible = e.Visible,
                    Deleted = e.Deleted,
                    CreatedOn = e.CreatedOn,
                    UpdatedOn = e.UpdatedOn,
                    ErrorText = e.ErrorText,
                }).ToList();
                data.Records = listResponse;
                data.CurrentPage = 1; // Set to current page if pagination is needed
                data.PageSize = 1; // Set appropriate page size
                data.TotalRecords = totalRecords;
                data.TotalPages = total_Pages; // Fix: Use the correct variable

            }

            return data;
        }


        [ExcludeFromCodeCoverage]
        public PageResponse<GlobalConfigurationUpdatePropertiesStatusResponse> GlobalPropertiesStatus(SearchRequest<GlobalConfigurationUpdatePropertiesStatus> filters, JwtTokenDetail userDetails)
        {
            if (userDetails == null)
                throw new UnauthorisedException(_utils.GetMessage("UserInvalid"));
            PageResponse<GlobalConfigurationUpdatePropertiesStatusResponse> data = new PageResponse<GlobalConfigurationUpdatePropertiesStatusResponse>();
            var response = _commonServiceProvider.GlobalPropertiesStatus(filters, userDetails);
            var firstRecord = response.FirstOrDefault();
            if (firstRecord != null)
            {
                var listResponse = response.Select(e => new GlobalConfigurationUpdatePropertiesStatusResponse()
                {
                  Message = e.message
                }).ToList();

                data.Records = listResponse;
                data.CurrentPage = 1; // Set to current page if pagination is needed
                data.PageSize = 1; // Set appropriate page size
                data.TotalRecords = 1;
                data.TotalPages = 1; // Fix: Use the correct variable

            }

            return data;
        }
        /// <summary>
        /// global properties value update for enable disable and update the value of global properties
        /// </summary>
        /// <param name="filters"></param>
        /// <param name="userDetails"></param>
        /// <returns></returns>
        /// <exception cref="UnauthorisedException"></exception>

        [ExcludeFromCodeCoverage]
        public PageResponse<GlobalConfigurationUpdatePropertiesValueResponse> GlobalPropertiesValue(SearchRequest<GlobalConfigurationUpdatePropertiesRequest> filters, JwtTokenDetail userDetails)
        {
            if (userDetails == null)
                throw new UnauthorisedException(_utils.GetMessage("UserInvalid"));
            PageResponse<GlobalConfigurationUpdatePropertiesValueResponse> data = new PageResponse<GlobalConfigurationUpdatePropertiesValueResponse>();
            var response = _commonServiceProvider.GlobalPropertiesValue(filters, userDetails);
            var firstRecord = response.FirstOrDefault();
            if (firstRecord != null)
            {
                var listResponse = response.Select(e => new GlobalConfigurationUpdatePropertiesValueResponse()
                {
                    Message = e.message
                }).ToList();

                data.Records = listResponse;
                data.CurrentPage = 1; // Set to current page if pagination is needed
                data.PageSize = 1; // Set appropriate page size
                data.TotalRecords = 1;
                data.TotalPages = 1; // Fix: Use the correct variable

            }

            return data;
        }
        /// <summary>
        /// Syncs Staffline users.
        /// </summary>
        /// <returns></returns>
        [ExcludeFromCodeCoverage]
        public async Task SyncStafflineUsersAsync()
        {
            try
            {
                var parameterService = new AwsParameterStoreService();
                var hasUsers = await _commonServiceProvider.HasStafflineUsersAsync();
                string StafflineApiUrl, StafflineApiAuthKey;
                var newReq = new StafflineSyncRequest
                {
                    LastUpdatedDateTime = hasUsers ? "" : "1900-01-01",
                    EmployeeIds = "",
                    SystemId = 0
                };
                var json = JsonSerializer.Serialize(newReq);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                StafflineApiUrl = parameterService.GetParameterValueAsync("/prod/userinsighttracking/StafflineApiUrl").Result;
                StafflineApiAuthKey = parameterService.GetParameterValueAsync("/prod/userinsighttracking/StafflineApiAuthKey").Result;
                
                _httpClient.DefaultRequestHeaders.Clear();
                _httpClient.DefaultRequestHeaders.Add("Authorization",
                    StafflineApiAuthKey);
                _httpClient.DefaultRequestHeaders.Add("accept", "*/*");

                var response = await _httpClient.PostAsync(
                    StafflineApiUrl, content);              

                var responseContent = await response.Content.ReadAsStringAsync();

                var result = JsonSerializer.Deserialize<StafflineUserResponse>(
                    responseContent,
                    new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

                if (result?.Data == null || !result.Data.Any())
                {
                    _logger.LogInformation("No records received from API.");
                    return;
                }

                await _commonServiceProvider.UpsertStafflineUsersAsync(result.Data);

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error during Staffline sync");               
            }
        }
    }
}
