using CashLineERP.Domain.Common;

namespace CashLineERP.Domain.Parties;

public sealed class OnboardingReviewFinding : Entity
{
    public long Id { get; private set; }
    public long WorkflowInstanceId { get; private set; }
    public string SubjectTypeCode { get; private set; } = string.Empty;
    public long SubjectProfileId { get; private set; }
    public string FindingCode { get; private set; } = string.Empty;
    public string SeverityCode { get; private set; } = string.Empty;
    public string? RelatedItemCode { get; private set; }
    public string StatusCode { get; private set; } = string.Empty;
    public string FindingText { get; private set; } = string.Empty;
    public DateTime LoggedAtUtc { get; private set; } = DateTime.UtcNow;
    public long LoggedByUserId { get; private set; }

    public OnboardingReviewFinding(
        long workflowInstanceId,
        string subjectTypeCode,
        long subjectProfileId,
        string findingCode,
        string severityCode,
        string? relatedItemCode,
        string statusCode,
        string findingText,
        long loggedByUserId)
    {
        if (workflowInstanceId <= 0 || subjectProfileId <= 0 || loggedByUserId <= 0)
        {
            throw new InvalidOperationException("Onboarding review finding requires valid workflow, profile, and reviewer identifiers.");
        }

        WorkflowInstanceId = workflowInstanceId;
        SubjectTypeCode = NormalizeRequired(subjectTypeCode, "subject type code");
        SubjectProfileId = subjectProfileId;
        FindingCode = NormalizeRequired(findingCode, "finding code");
        SeverityCode = NormalizeRequired(severityCode, "severity code");
        RelatedItemCode = NormalizeOptional(relatedItemCode);
        StatusCode = NormalizeRequired(statusCode, "status code");
        FindingText = NormalizeRequired(findingText, "finding text");
        LoggedByUserId = loggedByUserId;
        CreatedByUserId = loggedByUserId;
    }

    private OnboardingReviewFinding()
    {
    }

    private static string NormalizeRequired(string value, string fieldName)
    {
        var normalizedValue = NormalizeOptional(value);
        if (string.IsNullOrWhiteSpace(normalizedValue))
        {
            throw new InvalidOperationException($"Onboarding review finding {fieldName} is required.");
        }

        return normalizedValue;
    }

    private static string? NormalizeOptional(string? value) =>
        string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
