<?php

namespace App\Master\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\CronLog;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Mtc\MercuryDataModels\Tenant;

class CronLogController extends Controller
{
    /**
     * List recorded cron runs, defaulting to master (central) executions.
     *
     * @return array{logs: LengthAwarePaginator, tenants: list<array{id: string, name: string}>, commands: list<string>}
     */
    public function index(Request $request): array
    {
        $tenant = (string) $request->input('tenant', 'all');
        $command = (string) $request->input('command', 'all');
        $status = (string) $request->input('status', 'all');

        $logs = CronLog::query()
            ->when($tenant === 'master', fn ($query) => $query->system())
            ->when(
                $tenant !== '' && $tenant !== 'all' && $tenant !== 'master',
                fn ($query) => $query->forTenant($tenant)
            )
            ->when($command !== '' && $command !== 'all', fn ($query) => $query->ofCommand($command))
            ->when($status !== '' && $status !== 'all', fn ($query) => $query->where('status', $status))
            ->orderByDesc('started_at')
            ->paginate((int) $request->input('per_page', 25));

        return [
            'logs' => $logs,
            'tenants' => $this->tenantOptions(),
            'commands' => $this->commandOptions(),
        ];
    }

    /**
     * Distinct tenants that have cron logs, resolved to their site names.
     *
     * @return list<array{id: string, name: string}>
     */
    private function tenantOptions(): array
    {
        $tenantIds = CronLog::query()
            ->whereNotNull('tenant_id')
            ->distinct()
            ->orderBy('tenant_id')
            ->pluck('tenant_id');

        if ($tenantIds->isEmpty()) {
            return [];
        }

        $names = Tenant::query()->whereIn('id', $tenantIds)->pluck('name', 'id');

        return $tenantIds
            ->map(fn ($id) => ['id' => (string) $id, 'name' => (string) ($names[$id] ?? $id)])
            ->values()
            ->all();
    }

    /**
     * Distinct command names present in the logs, for the command filter.
     *
     * @return list<string>
     */
    private function commandOptions(): array
    {
        return CronLog::query()
            ->distinct()
            ->orderBy('command')
            ->pluck('command')
            ->all();
    }
}
