using AutoMapper;
using DevExpress.XtraPrinting.Native;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using WorkFlowCheck.MAUI.DataLayer;
using WorkFlowCheck.MAUI.Services.Interfaces;
using Android.Provider;
using Android.DeviceLock;
using WorkFlowCheck.MAUI.Helper;

namespace WorkFlowCheck.MAUI.Services
{

    public class BaseService
    {
        public readonly HttpClient _httpClient;
        public readonly AppDbContext _dbContext;

        public readonly IMapper _mapper;
        private string _deviceId;
        public string DeviceId => $"{_deviceId.ToUpper()}:{SystemHelper.DatabaseName}"; // Getter a DeviceId-hez   

        public BaseService(HttpClient httpClient, AppDbContext dbContext, IMapper mapper)
        {
            _httpClient = httpClient;
            _dbContext = dbContext;
            _mapper = mapper;

            var apiBaseUrl = SystemHelper.ApiBaseUrl;
            _httpClient.BaseAddress = new Uri(apiBaseUrl);

            var apiKey = SystemHelper.ApiKey;
            _httpClient.DefaultRequestHeaders.Add("X-Api-Key", apiKey);
            _deviceId = GetDeviceId();
        }
        protected async Task PrepareAuthenticatedRequestAsync()
        {
            var jwtToken = await SecureStorage.GetAsync("AuthToken");

            if (!string.IsNullOrEmpty(jwtToken) && _httpClient != null)
            {
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken);
                _httpClient.DefaultRequestHeaders.Add("DeviceId", _deviceId);
            }
        }
        protected string GetDeviceId()
        {
            try
            {
                var context = Android.App.Application.Context;
                return Settings.Secure.GetString(context.ContentResolver, Settings.Secure.AndroidId) ?? "NO_ANDROID_DEVICE";
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error retrieving device ID: {ex.Message}");
                return "UnknownDevice";
            }
        }
    }
}
