using System;
using System.Collections.Generic;
using EventsAppQuest.Web.Communication.Application;
using EventsAppQuest.Web.Domain;
using EventsAppQuest.Web.Producer.Application;
using EventsAppQuest.Web.Producer.Core;
using EventsAppQuest.Web.Producer.Domain;

namespace EventsAppQuest.Web.Application
{
    /// <summary>
    /// Geração formal do pedido operacional (ProducerOrder) a partir do CRM do hotel.
    /// Usa oportunidade, proposta e sessão Quest; monta OrderSummary e notas; mantém tudo em memória via HandoffStore.
    /// </summary>
    public static class HotelToProducerHandoffService
    {
        /// <summary>Gera um ProducerOrder a partir da oportunidade (e proposta/sessão quando existirem) e regista no HandoffStore.</summary>
        public static ProducerOrder GenerateOrder(string opportunityId, IReadOnlyList<SalesOpportunity> opportunities, IReadOnlyList<ProposalRecord> proposals, IReadOnlyList<SessionRecord> sessions)
        {
            SalesOpportunity opp = null;
            foreach (var o in opportunities ?? new List<SalesOpportunity>())
                if (o.Id == opportunityId) { opp = o; break; }
            if (opp == null) return null;

            ProposalRecord proposal = null;
            if (!string.IsNullOrEmpty(opp.ProposalRecordId) && proposals != null)
                foreach (var p in proposals)
                    if (p.Id == opp.ProposalRecordId) { proposal = p; break; }
            SessionRecord session = null;
            if (!string.IsNullOrEmpty(opp.SessionRecordId) && sessions != null)
                foreach (var s in sessions)
                    if (s.Id == opp.SessionRecordId) { session = s; break; }

            var orderId = "ord-" + Guid.NewGuid().ToString("N").Substring(0, 8);
            var now = DateTime.UtcNow;

            var notes = new List<string>();
            if (!string.IsNullOrEmpty(opp.SuggestedNextAction))
                notes.Add("Próxima ação comercial: " + opp.SuggestedNextAction);
            if (session != null)
            {
                if (!string.IsNullOrEmpty(session.SuggestedNextAction))
                    notes.Add("Sessão Quest – próxima ação: " + session.SuggestedNextAction);
                if (!string.IsNullOrEmpty(session.OutcomeSummary))
                    notes.Add("Sessão Quest – resumo: " + session.OutcomeSummary);
            }
            var salesHandoffNotes = string.Join(" | ", notes);
            if (string.IsNullOrEmpty(salesHandoffNotes))
                salesHandoffNotes = "Handoff da oportunidade " + opp.Title;

            var items = new List<string>();
            var hotspots = new List<string>();
            if (session != null && session.SuggestedNextAction != null)
                items.Add("Conforme sessão Quest: " + session.SuggestedNextAction);
            items.Add("Oportunidade: " + opp.Title);
            if (proposal != null)
                items.Add("Proposta: " + proposal.Name);

            var orderSummary = $"{opp.Title}. Proposta: {(proposal?.Name ?? "—")}. Sessão Quest: {(session != null ? session.SessionId ?? session.Id : "—")}. Prioridade: {opp.CommercialPriority}.";

            var order = new ProducerOrder
            {
                OrderId = orderId,
                OpportunityId = opp.Id,
                ProposalId = opp.ProposalRecordId,
                SessionId = opp.SessionRecordId ?? session?.SessionId,
                SourceLeadId = opp.LeadId,
                EventCategory = null,
                ThemeLabel = null,
                SelectedCommercialPackageLabel = null,
                RecommendedProposalId = session?.RecommendedProposalId ?? opp.LastQuestRecommendedProposalId,
                SelectedProposalId = session?.SelectedProposalId ?? opp.LastQuestSelectedProposalId,
                RequiredShowroomItems = items,
                KeyHotspots = hotspots,
                KeyNotesFromSales = notes,
                FollowUpPriority = session?.FollowUpPriority ?? opp.LastQuestFollowUpPriority ?? FollowUpPriority.Medium,
                ProducerOrderStatus = ProducerOrderStatus.New,
                CreatedAt = now,
                OrderSummary = orderSummary,
                AcceptanceStatus = ProducerAcceptanceStatus.PendingReview,
                RequiresClarification = false,
                ClarificationReason = null,
                SalesHandoffNotes = salesHandoffNotes,
                GeneratedAt = now,
                AcceptedAt = null,
                RejectedAt = null,
                LastUpdatedAt = now
            };

            if (proposal != null)
                order.ThemeLabel = "Proposta: " + proposal.Name;
            if (session != null)
            {
                order.KeyHotspots.Add("Sessão Quest: " + (session.SessionId ?? session.Id));
                if (!string.IsNullOrEmpty(session.ConfirmedCTA))
                    order.KeyNotesFromSales.Add("CTA confirmado: " + session.ConfirmedCTA);
            }

            HandoffStore.AddOrder(order);
            ProducerOrderCommunicationController.EnsureThreadForOrder(order.OrderId, order.OpportunityId, order.ProposalId, order.SessionId);
            return order;
        }
    }
}
