<?php

declare(strict_types=1);

namespace ImovelZapAi\Organizations\Application\Queries;

use App\Models\User;
use ImovelZapAi\Organizations\Application\Actions\EnsureOrganizationBootstrapAction;
use ImovelZapAi\Organizations\Infrastructure\Persistence\Eloquent\OrganizationSubscriptionModel;
use ImovelZapAi\Properties\Infrastructure\Persistence\Eloquent\PropertyModel;
use ImovelZapAi\Tenancy\Infrastructure\Persistence\Eloquent\TenantModel;

final class GetOrganizationPlanUsageQuery
{
    public function __construct(
        private readonly EnsureOrganizationBootstrapAction $bootstrap,
    ) {}

    /**
     * @return array{
     *     tenant: TenantModel,
     *     subscription: ?OrganizationSubscriptionModel,
     *     users_count: int,
     *     properties_count: int,
     *     max_users: int,
     *     max_properties: int,
     *     max_whatsapp_messages_month: int
     * }
     */
    public function execute(string $tenantId): array
    {
        $this->bootstrap->execute($tenantId);

        $tenant = TenantModel::query()->findOrFail($tenantId);
        $subscription = OrganizationSubscriptionModel::query()
            ->with('plan')
            ->where('tenant_id', $tenantId)
            ->first();

        $plan = $subscription?->plan;

        return [
            'tenant' => $tenant,
            'subscription' => $subscription,
            'users_count' => User::query()->where('tenant_id', $tenantId)->count(),
            'properties_count' => PropertyModel::query()->withoutGlobalScopes()->where('tenant_id', $tenantId)->count(),
            'max_users' => (int) ($plan?->max_users ?? 0),
            'max_properties' => (int) ($plan?->max_properties ?? 0),
            'max_whatsapp_messages_month' => (int) ($plan?->max_whatsapp_messages_month ?? 0),
        ];
    }
}
