<?php

namespace App\Http\Controllers\Api\Admin;

use App\Domains\Tenancy\Models\Tenant;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;

class AdminTenantIndexController extends Controller
{
    public function __invoke(): JsonResponse
    {
        $tenants = Tenant::query()
            ->with(['plan', 'users'])
            ->orderByDesc('created_at')
            ->get()
            ->map(fn (Tenant $tenant) => [
                'id' => $tenant->id,
                'companyName' => $tenant->company_name,
                'status' => $tenant->status,
                'plan' => $tenant->plan?->name ?? 'No plan',
                'planId' => $tenant->plan_id,
                'usersCount' => $tenant->users->count(),
                'trialEndsAt' => $tenant->trial_ends_at?->format('M d, Y'),
                'createdAt' => $tenant->created_at?->format('M d, Y'),
            ])
            ->values();

        return response()->json(['data' => $tenants]);
    }
}
