<?php

namespace App\Http\Controllers\Api\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Tenant;
use App\Services\Tenant\DashboardSummaryService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class DashboardController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        $tenant = $request->attributes->get('tenant');

        if (! $tenant instanceof Tenant) {
            $decoded = $request->attributes->get('decoded_token', []);
            $tenantId = Arr::get($decoded, 'tenant_id');

            if ($tenantId) {
                $tenant = Tenant::query()->find($tenantId);
            }
        }

        if (! $tenant instanceof Tenant) {
            return response()->json([
                'message' => 'Tenant context missing.',
            ], 401);
        }

        $summary = app(DashboardSummaryService::class)->build($tenant);

        return response()->json($summary);
    }
}
