// DBIS IRU .NET SDK
// Client library for IRU integration

using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace DBIS.IRU.SDK
{
    /// <summary>
    /// DBIS IRU Client
    /// </summary>
    public class IRUClient
    {
        private readonly string apiBaseUrl;
        private readonly string apiKey;
        private readonly HttpClient httpClient;
        private readonly JsonSerializerOptions jsonOptions;

        public IRUClient(string apiBaseUrl, string apiKey = null)
        {
            this.apiBaseUrl = apiBaseUrl.TrimEnd('/');
            this.apiKey = apiKey;
            this.httpClient = new HttpClient
            {
                Timeout = TimeSpan.FromSeconds(30)
            };
            
            if (!string.IsNullOrEmpty(apiKey))
            {
                this.httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            }
            
            this.httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json");
            
            this.jsonOptions = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };
        }

        /// <summary>
        /// Get all IRU offerings
        /// </summary>
        public async Task<IRUOffering[]> GetOfferingsAsync(
            int? capacityTier = null,
            string institutionalType = null
        )
        {
            var url = $"{apiBaseUrl}/api/v1/iru/marketplace/offerings";
            var queryParams = new System.Collections.Specialized.NameValueCollection();
            
            if (capacityTier.HasValue)
            {
                queryParams.Add("capacityTier", capacityTier.Value.ToString());
            }
            if (!string.IsNullOrEmpty(institutionalType))
            {
                queryParams.Add("institutionalType", institutionalType);
            }

            if (queryParams.Count > 0)
            {
                var queryString = string.Join("&", 
                    Array.ConvertAll(queryParams.AllKeys, 
                        key => $"{key}={Uri.EscapeDataString(queryParams[key])}"));
                url += "?" + queryString;
            }

            var response = await httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();
            
            var json = await response.Content.ReadAsStringAsync();
            var result = JsonSerializer.Deserialize<ApiResponse<IRUOffering[]>>(json, jsonOptions);
            
            return result.Data;
        }

        /// <summary>
        /// Submit inquiry
        /// </summary>
        public async Task<InquiryResult> SubmitInquiryAsync(IRUInquiry inquiry)
        {
            var url = $"{apiBaseUrl}/api/v1/iru/marketplace/inquiries";
            var json = JsonSerializer.Serialize(inquiry, jsonOptions);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            var response = await httpClient.PostAsync(url, content);
            response.EnsureSuccessStatusCode();

            var responseJson = await response.Content.ReadAsStringAsync();
            var result = JsonSerializer.Deserialize<ApiResponse<InquiryResult>>(responseJson, jsonOptions);

            return result.Data;
        }

        /// <summary>
        /// Get dashboard
        /// </summary>
        public async Task<DashboardData> GetDashboardAsync()
        {
            var url = $"{apiBaseUrl}/api/v1/iru/portal/dashboard";
            var response = await httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();

            var json = await response.Content.ReadAsStringAsync();
            var result = JsonSerializer.Deserialize<ApiResponse<DashboardData>>(json, jsonOptions);

            return result.Data;
        }
    }

    public class ApiResponse<T>
    {
        public bool Success { get; set; }
        public T Data { get; set; }
    }

    public class IRUOffering
    {
        public string Id { get; set; }
        public string OfferingId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public int CapacityTier { get; set; }
        public string InstitutionalType { get; set; }
        public decimal? BasePrice { get; set; }
        public string Currency { get; set; }
    }

    public class IRUInquiry
    {
        public string OfferingId { get; set; }
        public string OrganizationName { get; set; }
        public string InstitutionalType { get; set; }
        public string Jurisdiction { get; set; }
        public string ContactEmail { get; set; }
        public string ContactPhone { get; set; }
        public string ContactName { get; set; }
        public string EstimatedVolume { get; set; }
        public DateTime? ExpectedGoLive { get; set; }
    }

    public class InquiryResult
    {
        public string InquiryId { get; set; }
        public string Status { get; set; }
        public string Message { get; set; }
    }

    public class DashboardData
    {
        public object Subscription { get; set; }
        public object DeploymentStatus { get; set; }
        public object ServiceHealth { get; set; }
    }
}
