using CashLineERP.Contracts.Parties;

namespace CashLineERP.Application.Parties;

public sealed class OnboardingReviewService : IOnboardingReviewService
{
    private readonly IOnboardingReviewRepository _repository;

    public OnboardingReviewService(IOnboardingReviewRepository repository)
    {
        _repository = repository;
    }

    public OnboardingReviewCaseResponse GetSupplierReviewCase(long supplierProfileId) => Map(_repository.GetReviewCase("SUPPLIER", supplierProfileId));
    public OnboardingReviewCaseResponse GetCustomerReviewCase(long customerProfileId) => Map(_repository.GetReviewCase("CUSTOMER", customerProfileId));
    public OnboardingReviewCaseResponse UpsertSupplierChecklistItems(long supplierProfileId, long actorUserId, IReadOnlyCollection<UpsertOnboardingReviewChecklistItemRequest> items) => Map(_repository.UpsertChecklistItems("SUPPLIER", supplierProfileId, actorUserId, items.Select(Map).ToArray()));
    public OnboardingReviewCaseResponse UpsertCustomerChecklistItems(long customerProfileId, long actorUserId, IReadOnlyCollection<UpsertOnboardingReviewChecklistItemRequest> items) => Map(_repository.UpsertChecklistItems("CUSTOMER", customerProfileId, actorUserId, items.Select(Map).ToArray()));
    public OnboardingReviewCaseResponse AddSupplierFinding(long supplierProfileId, long actorUserId, CreateOnboardingReviewFindingRequest finding) => Map(_repository.AddFinding("SUPPLIER", supplierProfileId, actorUserId, Map(finding)));
    public OnboardingReviewCaseResponse AddCustomerFinding(long customerProfileId, long actorUserId, CreateOnboardingReviewFindingRequest finding) => Map(_repository.AddFinding("CUSTOMER", customerProfileId, actorUserId, Map(finding)));

    private static UpsertOnboardingReviewChecklistItemCommand Map(UpsertOnboardingReviewChecklistItemRequest request) =>
        new(request.ChecklistItemCode, request.DisplayName, request.StatusCode, request.CoverageCode, request.ReviewerNotes);

    private static CreateOnboardingReviewFindingCommand Map(CreateOnboardingReviewFindingRequest request) =>
        new(request.FindingCode, request.SeverityCode, request.RelatedItemCode, request.StatusCode, request.FindingText);

    private static OnboardingReviewCaseResponse Map(OnboardingReviewCaseView view) =>
        new(
            view.SubjectTypeCode,
            view.SubjectProfileId,
            view.WorkflowInstanceId,
            view.WorkflowStatusCode,
            view.ChecklistItems.Select(item => new OnboardingReviewChecklistItemResponse(item.OnboardingReviewChecklistItemId, item.ChecklistItemCode, item.DisplayName, item.StatusCode, item.CoverageCode, item.ReviewerNotes, item.ReviewedAtUtc, item.ReviewedByUserId)).ToArray(),
            view.Findings.Select(finding => new OnboardingReviewFindingResponse(finding.OnboardingReviewFindingId, finding.FindingCode, finding.SeverityCode, finding.RelatedItemCode, finding.StatusCode, finding.FindingText, finding.LoggedAtUtc, finding.LoggedByUserId)).ToArray());
}
