<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\QueueProcessLog;

class QueueProcessLogController extends Controller
{
    public function index(Request $request)
    {
        $perPage = $request->input('per_page', 50);

        return [
            'process_types' => QueueProcessLog::query()->distinct()->pluck('process_type')
                ->filter()
                ->map(fn($type) => [
                    'id' => $type,
                    'name' => ucwords(str_replace('_', ' ', $type))
                ])->prepend(['id' => 'all', 'name' => 'All']),
            'providers' => QueueProcessLog::query()->distinct()->pluck('provider')
                ->filter()
                ->map(fn($provider) => [
                    'id' => $provider,
                    'name' => $provider
                ])->prepend(['id' => 'all', 'name' => 'All']),
            'statuses' => collect([
                ['id' => 'all', 'name' => 'All'],
                ['id' => QueueProcessLog::STATUS_RUNNING, 'name' => 'Running'],
                ['id' => QueueProcessLog::STATUS_COMPLETED, 'name' => 'Completed'],
                ['id' => QueueProcessLog::STATUS_FAILED, 'name' => 'Failed'],
            ]),
            'logs' => QueueProcessLog::query()
                ->latest('id')
                ->when(
                    $request->filled('process_type') && $request->input('process_type') !== 'all',
                    fn($query) => $query->where('process_type', $request->input('process_type'))
                )
                ->when(
                    $request->filled('provider') && $request->input('provider') !== 'all',
                    fn($query) => $query->where('provider', $request->input('provider'))
                )
                ->when(
                    $request->filled('status') && $request->input('status') !== 'all',
                    fn($query) => $query->where('status', $request->input('status'))
                )
                ->when(
                    $request->filled('days'),
                    fn($query) => $query->where(
                        'started_at',
                        '>=',
                        Carbon::now()->subDays((int) $request->input('days'))
                    )
                )
                ->paginate($perPage),
        ];
    }

    public function show(QueueProcessLog $queueProcessLog)
    {
        return $queueProcessLog;
    }
}
