<?php

namespace App\Http\Controllers\Meet\Concerns;

use App\Models\Room;
use App\Services\Billing\BillingClient;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

trait BuildsMeetIndexPage
{
    /**
     * @return array<int, array{value: string, label: string}>
     */
    protected function meetIndexStats(Request $request, Builder $roomQuery, string $countLabel, string $secondaryLabel): array
    {
        $owner = $this->ownerRef($request);
        $organization = $this->organization($request);

        $balance = '—';
        try {
            $minor = app(BillingClient::class)->balanceMinor($owner);
            $currency = (string) config('billing.currency', 'GHS');
            $balance = $currency.' '.number_format($minor / 100, 2);
        } catch (\Throwable) {
            // Wallet API unavailable — show placeholder.
        }

        $total = (clone $roomQuery)->count();
        $live = (clone $roomQuery)->where('status', 'live')->count();

        return [
            ['value' => $balance, 'label' => 'Account balance'],
            ['value' => (string) $total, 'label' => $countLabel],
            ['value' => (string) $live, 'label' => $secondaryLabel],
        ];
    }

    /**
     * @return array<int, array{title: string, subtitle: string, meta: string, status: string, url: string, active: bool}>
     */
    protected function meetIndexItems(iterable $rooms, callable $detailsUrl): array
    {
        $items = [];

        foreach ($rooms as $room) {
            /** @var Room $room */
            $typeLabel = match (true) {
                $room->isSpace() => 'Room',
                $room->isWebinar() => 'Webinar',
                $room->isConference() => 'Conference',
                default => ucfirst(config('meet.room_types')[$room->type] ?? $room->type),
            };

            $schedule = $room->scheduled_at
                ? $room->scheduled_at->timezone($room->timezone)->format('M j, Y g:i A')
                : ($room->isConference() ? 'Instant conference' : ($room->isSpace() ? 'Audio room' : 'Instant meeting'));

            $statusLabel = config('meet.room_statuses')[$room->status] ?? ucfirst($room->status);

            $items[] = [
                'title' => $room->title,
                'subtitle' => $typeLabel.' · '.$room->joinUrl(),
                'meta' => $schedule,
                'status' => $statusLabel,
                'url' => $detailsUrl($room),
                'active' => $room->status !== 'cancelled' && $room->status !== 'ended',
            ];
        }

        return $items;
    }

}
