using CashLineERP.Domain.Common;
using CashLineERP.SharedKernel.Workflow;

namespace CashLineERP.Domain.Procurement;

public sealed class RfqEvaluation : Entity
{
    public long Id { get; private set; }

    public long RequestForQuotationId { get; private set; }

    public string EvaluationNumber { get; private set; } = string.Empty;

    public DateOnly EvaluationDate { get; private set; }

    public long StatusId { get; private set; } = WorkflowStatusSeedIds.Draft;

    public long? RecommendedSupplierId { get; private set; }

    public long? ApprovedQuotationId { get; private set; }

    public string? Notes { get; private set; }

    public List<RfqEvaluationLine> Lines { get; private set; } = [];

    public RfqEvaluation(
        long requestForQuotationId,
        string evaluationNumber,
        DateOnly evaluationDate,
        string? notes)
    {
        RequestForQuotationId = requestForQuotationId;
        EvaluationNumber = evaluationNumber;
        EvaluationDate = evaluationDate;
        Notes = notes;
    }

    private RfqEvaluation()
    {
    }

    public void AddLine(
        long quotationId,
        long supplierId,
        decimal? priceScore,
        decimal? commercialScore,
        decimal? deliveryScore,
        decimal? qualityScore,
        int rankNumber,
        bool isRecommended,
        string? notes)
    {
        var totalScore = (priceScore ?? 0m) + (commercialScore ?? 0m) + (deliveryScore ?? 0m) + (qualityScore ?? 0m);

        Lines.Add(new RfqEvaluationLine(
            evaluationId: Id,
            quotationId: quotationId,
            supplierId: supplierId,
            priceScore: priceScore,
            commercialScore: commercialScore,
            deliveryScore: deliveryScore,
            qualityScore: qualityScore,
            totalScore: totalScore,
            rankNumber: rankNumber,
            isRecommended: isRecommended,
            notes: notes));

        if (isRecommended)
        {
            RecommendedSupplierId = supplierId;
            ApprovedQuotationId = quotationId;
        }
    }

    public void FinalizeRecommendation(long actorUserId)
    {
        StatusId = WorkflowStatusSeedIds.Approved;
        Touch(actorUserId);
    }
}
