<?php

declare(strict_types=1);

namespace ImovelZapAi\ClientPortal\Application\Queries;

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\PortalActivityModel;
use ImovelZapAi\ClientPortal\Infrastructure\Persistence\Eloquent\RequestedDocumentModel;

final class GetClientPortalDashboardQuery
{
    /**
     * @return array<string, mixed>
     */
    public function execute(string $tenantId): array
    {
        $active = ClientPortalModel::query()
            ->where('tenant_id', $tenantId)
            ->where('status', PortalStatus::Active)
            ->count();

        $expired = ClientPortalModel::query()
            ->where('tenant_id', $tenantId)
            ->where(function ($q): void {
                $q->where('status', PortalStatus::Expired)
                    ->orWhere(function ($q2): void {
                        $q2->where('status', PortalStatus::Active)
                            ->whereNotNull('expires_at')
                            ->where('expires_at', '<', now());
                    });
            })
            ->count();

        $uploadedToday = PortalActivityModel::query()
            ->where('tenant_id', $tenantId)
            ->where('event', 'document_uploaded')
            ->whereDate('created_at', now()->toDateString())
            ->count();

        $pendingReview = RequestedDocumentModel::query()
            ->where('tenant_id', $tenantId)
            ->whereIn('status', [
                RequestedDocumentStatus::UnderReview->value,
                RequestedDocumentStatus::UnderAnalysis->value,
                RequestedDocumentStatus::Uploaded->value,
            ])
            ->count();

        $completed = ClientPortalModel::query()
            ->where('tenant_id', $tenantId)
            ->where('status', PortalStatus::Completed)
            ->whereNotNull('completed_at')
            ->whereNotNull('created_at')
            ->get(['created_at', 'completed_at']);

        $avgHours = null;
        if ($completed->isNotEmpty()) {
            $avgHours = round(
                $completed->avg(fn (ClientPortalModel $p) => $p->created_at->diffInMinutes($p->completed_at) / 60),
                1,
            );
        }

        return [
            'active_portals' => $active,
            'uploaded_today' => $uploadedToday,
            'pending_review' => $pendingReview,
            'expired_portals' => $expired,
            'avg_completion_hours' => $avgHours,
        ];
    }
}
