<?php

namespace App\Modules\Admin\Operations\Services;

use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\Admin\Tenancy\Models\Subscription;
use App\Modules\Exports\Models\Export;
use App\Modules\Integrations\Platform\Models\IntegrationWebhookDelivery;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class BusinessMetricsService
{
    /**
     * @return array<string, mixed>
     */
    public function snapshot(): array
    {
        $activeTenants = Tenant::query()->where('is_active', true)->count();
        $byLifecycle = Tenant::query()
            ->selectRaw('lifecycle_state, count(*) as c')
            ->groupBy('lifecycle_state')
            ->pluck('c', 'lifecycle_state')
            ->all();

        $subs = Subscription::query()
            ->selectRaw('status, count(*) as c')
            ->groupBy('status')
            ->pluck('c', 'status')
            ->all();

        $exports24h = Export::query()->withoutGlobalScopes()
            ->where('created_at', '>=', now()->subDay())
            ->count();

        $webhookFail24h = IntegrationWebhookDelivery::query()
            ->whereIn('status', ['failed', 'dead_letter'])
            ->where('updated_at', '>=', now()->subDay())
            ->count();

        $api24h = Schema::hasTable('api_audit_logs')
            ? (int) DB::table('api_audit_logs')
                ->where('created_at', '>=', now()->subDay())
                ->count()
            : 0;

        return [
            'tenants_active' => $activeTenants,
            'tenants_by_lifecycle' => $byLifecycle,
            'subscriptions_by_status' => $subs,
            'exports_last_24h' => $exports24h,
            'webhook_failures_last_24h' => $webhookFail24h,
            'api_audit_events_last_24h' => $api24h,
        ];
    }
}
