using System.Text.Json;
using CMSMicroservice.Protobuf.Protos.SitePageSettings;

namespace FrontOffice.Main.Utilities;

/// <summary>
/// سرویس ساده‌شده مدیریت صفحات سایت
/// ۴ صفحه ثابت: landing, about, contact, licenses
/// </summary>
public class SitePageSettingsService
{
    private readonly SitePageSettingsContract.SitePageSettingsContractClient _client;

    public SitePageSettingsService(SitePageSettingsContract.SitePageSettingsContractClient client)
    {
        _client = client;
    }

    /// <summary>
    /// دریافت تنظیمات صفحه با کلید
    /// </summary>
    public async Task<PageSettingsDto?> GetPageAsync(string pageKey)
    {
        try
        {
            var response = await _client.GetPageSettingsAsync(
                new GetPageSettingsRequest { PageKey = pageKey });

            if (response == null || response.Id <= 0) return null;

            return MapToDto(response);
        }
        catch (Exception ex)
        {
#if DEBUG
            Console.WriteLine($"SitePageSettingsService.GetPageAsync error: {ex.Message}");
#endif
            return null;
        }
    }

    private static PageSettingsDto MapToDto(PageSettingsResponse response) => new()
    {
        Id = response.Id,
        PageKey = response.PageKey,
        Title = response.Title,
        MetaDescription = response.MetaDescription,
        HeroTitle = response.HeroTitle,
        HeroSubtitle = response.HeroSubtitle,
        HeroImagePath = response.HeroImagePath,
        IsActive = response.IsActive,
        SettingsJson = response.SettingsJson,
        Images = response.Images.Select(i => new PageSettingsImageDto
        {
            Id = i.Id,
            ImageGroup = i.ImageGroup,
            Title = i.Title,
            Subtitle = i.Subtitle,
            Description = i.Description,
            ImagePath = i.ImagePath,
            ThumbnailPath = i.ThumbnailPath,
            LinkUrl = i.LinkUrl,
            IconName = i.IconName,
            SortOrder = i.SortOrder,
            IsActive = i.IsActive
        }).OrderBy(i => i.SortOrder).ToList()
    };
}

// ── DTOs ──

public class PageSettingsDto
{
    public long Id { get; set; }
    public string PageKey { get; set; } = string.Empty;
    public string Title { get; set; } = string.Empty;
    public string? MetaDescription { get; set; }
    public string? HeroTitle { get; set; }
    public string? HeroSubtitle { get; set; }
    public string? HeroImagePath { get; set; }
    public bool IsActive { get; set; }
    public string? SettingsJson { get; set; }
    public List<PageSettingsImageDto> Images { get; set; } = new();

    /// <summary>
    /// دریافت تصاویر یک گروه خاص
    /// </summary>
    public List<PageSettingsImageDto> GetImages(string group) =>
        Images.Where(i => i.ImageGroup == group && i.IsActive)
              .OrderBy(i => i.SortOrder).ToList();

    /// <summary>
    /// دریافت تنظیمات JSON به عنوان یک نوع مشخص
    /// </summary>
    public T? GetSettings<T>() where T : class
    {
        if (string.IsNullOrWhiteSpace(SettingsJson)) return null;
        try
        {
            return JsonSerializer.Deserialize<T>(SettingsJson, new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            });
        }
        catch
        {
            return null;
        }
    }
}

public class PageSettingsImageDto
{
    public long Id { get; set; }
    public string ImageGroup { get; set; } = string.Empty;
    public string? Title { get; set; }
    public string? Subtitle { get; set; }
    public string? Description { get; set; }
    public string ImagePath { get; set; } = string.Empty;
    public string? ThumbnailPath { get; set; }
    public string? LinkUrl { get; set; }
    public string? IconName { get; set; }
    public int SortOrder { get; set; }
    public bool IsActive { get; set; }
}
