using System.Text;
using KiMailOrderAgent.Models;
using System.Linq;

namespace KiMailOrderAgent.Approval;

public class ApprovalMessageBuilder
{
    public string Build(ExtractedOrder order)
    {
        var sb = new StringBuilder();

        sb.AppendLine("📦 Neue Bestellung erkannt");
        sb.AppendLine($"Bestell-ID: {order.Id}");
        sb.AppendLine();
        sb.AppendLine($"Von: {order.OriginalMailFrom}");
        sb.AppendLine($"Betreff: {order.OriginalMailSubject}");
        sb.AppendLine();

        sb.AppendLine("👤 Kunde:");
        sb.AppendLine($"{order.Customer.CompanyName}");
        sb.AppendLine($"{order.Customer.ContactName}");
        sb.AppendLine($"{order.Customer.Street}");
        sb.AppendLine($"{order.Customer.ZipCode} {order.Customer.City}");
        sb.AppendLine();

        var riskyItems = order.Items
        .Where(x => x.Confidence < 0.8 || string.IsNullOrWhiteSpace(x.ArticleNumber))
        .ToList();

        if (riskyItems.Any())
        {
            sb.AppendLine("⚠️ Hinweise / Unsicherheiten:");
            sb.AppendLine();

            foreach (var item in riskyItems)
            {
                sb.AppendLine($"- {item.Description}");
                sb.AppendLine($"  Artikelnummer: {item.ArticleNumber ?? "NICHT ERKANNT"}");
                sb.AppendLine($"  Sicherheit: {item.Confidence:P0}");
                sb.AppendLine($"  Grund: {item.Reason}");
                sb.AppendLine();
            }
        }

        sb.AppendLine("📋 Positionen:");

        foreach (var item in order.Items)
        {
            sb.AppendLine($"- {item.Quantity}x {item.Description} ({item.ArticleNumber})");
            sb.AppendLine($"  Sicherheit: {item.Confidence:P0}");
            sb.AppendLine($"  Grund: {item.Reason}");
        }

        sb.AppendLine();
        sb.AppendLine($"🤖 Confidence: {order.Confidence:P}");
        sb.AppendLine();
        sb.AppendLine("Status: WARTET AUF FREIGABE");
        sb.AppendLine();
        sb.AppendLine("Antwortmöglichkeiten:");
        sb.AppendLine("OK");
        sb.AppendLine("ABLEHNEN");
        sb.AppendLine("KORREKTUR: ...");

        return sb.ToString();
    }
}