using JSMR.Application.Scanning.Ports;
using JSMR.Domain.Entities;
using JSMR.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using System.Text;

namespace JSMR.Infrastructure.Ingestion;

public class VoiceWorkSearchUpdater(AppDbContext dbContext) : IVoiceWorkSearchUpdater
{
    public async Task UpdateAsync(int[] voiceWorkIds, CancellationToken cancellationToken)
    {
        List<VoiceWork> batch = await dbContext.VoiceWorks
                .Where(vw => voiceWorkIds.Contains(vw.VoiceWorkId))
                .AsSplitQuery()
                .Include(vw => vw.Circle)
                .Include(vw => vw.Tags)
                    .ThenInclude(vwt => vwt.Tag)
                .Include(vw => vw.Creators)
                    .ThenInclude(vwc => vwc.Creator)
                .Include(vw => vw.EnglishVoiceWorks)
                .ToListAsync(cancellationToken);

        foreach (var voiceWork in batch)
        {
            try
            {
                UpdateSearchText(voiceWork);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"⚠️ Error updating VoiceWorkId {voiceWork.VoiceWorkId}: {ex.Message}");
            }
        }

        dbContext.SaveChanges();
    }

    private void UpdateSearchText(VoiceWork voiceWork)
    {
        string searchText = GetSearchText(voiceWork);

        var searchEntry = dbContext.VoiceWorkSearches
            .FirstOrDefault(s => s.VoiceWorkId == voiceWork.VoiceWorkId);

        if (searchEntry == null)
        {
            dbContext.VoiceWorkSearches.Add(new VoiceWorkSearch
            {
                VoiceWorkId = voiceWork.VoiceWorkId,
                SearchText = searchText
            });
        }
        else
        {
            searchEntry.SearchText = searchText;
        }
    }

    private string GetSearchText(VoiceWork voiceWork)
    {
        var english = voiceWork.EnglishVoiceWorks.FirstOrDefault();

        var sb = new StringBuilder();

        AppendRaw(sb, voiceWork.ProductId);
        AppendRaw(sb, voiceWork.Circle?.MakerId);

        AppendRaw(sb, english?.ProductName);
        AppendRaw(sb, english?.Description);

        AppendRaw(sb, voiceWork.ProductName);
        AppendRaw(sb, voiceWork.Description);
        AppendRaw(sb, voiceWork.Circle?.Name);

        foreach (var tag in voiceWork.Tags.Select(vwt => vwt.Tag))
        {
            if (tag is null)
                continue;

            AppendRaw(sb, tag.Name);

            var englishTag = dbContext.EnglishTags.FirstOrDefault(et => et.TagId == tag.TagId);

            if (englishTag is null)
                continue;

            AppendRaw(sb, englishTag?.Name);
        }

        foreach (var creator in voiceWork.Creators.Select(vwc => vwc.Creator))
        {
            if (creator is null)
                continue;

            AppendRaw(sb, creator?.Name);
        }

        string searchText = sb.ToString().Trim();

        return searchText;
    }

    private static void AppendRaw(StringBuilder sb, string? text)
    {
        if (!string.IsNullOrWhiteSpace(text))
            sb.Append(text).Append(' ');
    }
}