<?php

namespace App\Http\Controllers\Api\Admin;

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

class AdminTenantShowController extends Controller
{
    public function __invoke(string $tenant): JsonResponse
    {
        $record = Tenant::query()
            ->with(['plan', 'users', 'subscriptions', 'channelAccounts', 'paymentProviders'])
            ->findOrFail($tenant);

        return response()->json([
            'data' => [
                'id' => $record->id,
                'companyName' => $record->company_name,
                'status' => $record->status,
                'plan' => $record->plan?->name ?? 'No plan',
                'trialEndsAt' => $record->trial_ends_at?->format('M d, Y'),
                'timezone' => $record->timezone,
                'currencyCode' => $record->currency_code,
                'usersCount' => $record->users->count(),
                'subscriptions' => $record->subscriptions->map(fn ($subscription) => [
                    'id' => $subscription->id,
                    'status' => $subscription->status,
                    'startsAt' => $subscription->starts_at?->format('M d, Y'),
                    'trialEndsAt' => $subscription->trial_ends_at?->format('M d, Y'),
                    'endsAt' => $subscription->ends_at?->format('M d, Y'),
                ])->values()->all(),
                'channels' => $record->channelAccounts->map(fn ($channel) => [
                    'id' => $channel->id,
                    'type' => $channel->type,
                    'status' => $channel->status,
                ])->values()->all(),
                'paymentProviders' => $record->paymentProviders->map(fn ($provider) => [
                    'id' => $provider->id,
                    'providerKey' => $provider->provider_key,
                    'enabled' => $provider->is_enabled,
                ])->values()->all(),
            ],
        ]);
    }
}
