<?php

declare(strict_types=1);

namespace Maestro\Core\Modules\HourRegistration\Services;

use Maestro\Core\Modules\HourRegistration\Enums\HourLineApprovalStatus;
use Maestro\Core\Modules\HourRegistration\Enums\HourWorkflowStatus;
use Maestro\Core\Modules\HourRegistration\Models\HourTimesheetWeek;

final class HourWeekWorkflowStatusService
{
    public function __construct(
        private readonly HourApproverResolver $approverResolver,
    ) {}

    public function refreshAggregateStatus(HourTimesheetWeek $week): void
    {
        $week->loadMissing('lines');

        if ($week->workflow_status === HourWorkflowStatus::Draft) {
            return;
        }

        $requiresApprovalLines = $week->lines->filter(
            fn ($line) => $this->approverResolver->lineRequiresLeadApproval($line),
        );

        if ($requiresApprovalLines->contains(
            fn ($line) => $line->line_approval_status === HourLineApprovalStatus::Rejected,
        )) {
            $week->workflow_status = HourWorkflowStatus::Rejected;

            $week->saveQuietly();

            return;
        }

        $stillPending = $requiresApprovalLines->contains(
            fn ($line) => $line->line_approval_status === HourLineApprovalStatus::Pending,
        );

        if ($stillPending) {
            $week->workflow_status = HourWorkflowStatus::Submitted;

            $week->saveQuietly();

            return;
        }

        $week->workflow_status = HourWorkflowStatus::Approved;

        $week->saveQuietly();
    }
}
