<?php

declare(strict_types=1);

namespace ImovelZapAi\ClientPortal\Application\Services;

use ImovelZapAi\ClientPortal\Domain\Enums\PortalStatus;
use ImovelZapAi\ClientPortal\Domain\Enums\RequestedDocumentStatus;
use ImovelZapAi\ClientPortal\Infrastructure\Persistence\Eloquent\ClientPortalModel;
use ImovelZapAi\ClientPortal\Infrastructure\Persistence\Eloquent\RequestedDocumentModel;

final class PortalProgressCalculator
{
    public function refresh(ClientPortalModel $portal): ClientPortalModel
    {
        $docs = RequestedDocumentModel::query()
            ->where('client_portal_id', $portal->id)
            ->get();

        $total = $docs->count();
        $approved = $docs->where('status', RequestedDocumentStatus::Approved)->count();
        $submitted = $docs->filter(
            fn (RequestedDocumentModel $d) => $d->status->countsAsSubmitted()
        )->count();

        $portal->forceFill([
            'documents_total' => $total,
            'documents_approved' => $approved,
            'documents_submitted' => $submitted,
            'last_activity_at' => now(),
        ]);

        if ($total > 0 && $approved === $total && $portal->status === PortalStatus::Active) {
            $portal->forceFill([
                'status' => PortalStatus::Completed,
                'completed_at' => now(),
            ]);
        }

        $portal->save();

        return $portal->fresh();
    }
}
