<?php

namespace App\Modules\Admin\Operations\Services;

use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\Admin\Tenancy\Repositories\SubscriptionRepository;
use App\Modules\Admin\Billing\Repositories\InvoiceRepository;
use App\Modules\Exports\Models\Export;
use App\Modules\Exports\Support\ExportStatus;
use App\Modules\Integrations\Platform\Models\IntegrationWebhookDelivery;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class TenantDiagnosticsService
{
    public function __construct(
        private readonly SubscriptionRepository $subscriptions,
        private readonly InvoiceRepository $invoices,
    ) {}

    /**
     * @return array<string, mixed>
     */
    public function snapshot(Tenant $tenant): array
    {
        $tid = (int) $tenant->id;
        $sub = $this->subscriptions->latestFor($tenant);

        $exports = Export::query()
            ->withoutGlobalScopes()
            ->where('tenant_id', $tid)
            ->selectRaw('status, count(*) as c')
            ->groupBy('status')
            ->pluck('c', 'status')
            ->all();

        $webhookIssues = IntegrationWebhookDelivery::query()
            ->where('tenant_id', $tid)
            ->whereIn('status', ['failed', 'dead_letter'])
            ->where('created_at', '>=', now()->subDays(14))
            ->count();

        $apiCalls = Schema::hasTable('api_audit_logs')
            ? (int) DB::table('api_audit_logs')
                ->where('tenant_id', $tid)
                ->where('created_at', '>=', now()->subDays(7))
                ->count()
            : 0;

        return [
            'tenant' => [
                'id' => $tid,
                'name' => $tenant->name,
                'lifecycle_state' => $tenant->lifecycle_state,
                'is_active' => (bool) $tenant->is_active,
                'locale' => $tenant->locale,
                'timezone' => $tenant->timezone,
            ],
            'subscription' => $sub ? [
                'id' => (int) $sub->id,
                'status' => $sub->status,
                'ends_at' => $sub->ends_at?->toIso8601String(),
                'grace_ends_at' => $sub->grace_ends_at?->toIso8601String(),
            ] : null,
            'exports_by_status' => $exports,
            'exports_pending' => (int) (Export::query()
                ->withoutGlobalScopes()
                ->where('tenant_id', $tid)
                ->where('status', ExportStatus::PENDING)
                ->count()),
            'open_invoices' => $this->invoices->countOpenForTenant($tid),
            'webhook_failures_14d' => $webhookIssues,
            'api_requests_7d' => $apiCalls,
        ];
    }
}
