<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Mtc\MercuryDataModels\ApiNotification;

class ApiLogController extends Controller
{
    public function index(Request $request)
    {
        return [
            'providers' => ApiNotification::query()->distinct()->pluck('provider')
                ->filter()
                ->map(fn($provider) => [
                    'id' => $provider,
                    'name' => $provider
                ])->prepend(['id' => 'all', 'name' => 'All']),
            'types' => ApiNotification::query()->distinct()->pluck('data_model')
                ->filter()
                ->map(fn($model) => [
                    'id' => $model,
                    'name' => $model
                ])->prepend(['id' => 'all', 'name' => 'All']),
            'references' => ApiNotification::query()->distinct()->pluck('reference')
                ->filter()
                ->map(fn($reference) => [
                    'id' => $reference,
                    'name' => $reference
                ])->prepend(['id' => 'all', 'name' => 'All']),
            'logs' => ApiNotification::query()
                ->latest()
                ->when(
                    $request->filled('provider') && $request->input('provider') !== 'all',
                    fn($query) => $query->where('provider', $request->input('provider'))
                )
                ->when(
                    $request->filled('data_model') && $request->input('data_model') !== 'all',
                    fn($query) => $query->where('data_model', $request->input('data_model'))
                )
                ->when(
                    $request->filled('reference') && $request->input('reference') !== 'all',
                    fn($query) => $query->where('reference', $request->input('reference'))
                )
                ->when(
                    !empty($request->input('term')),
                    fn($query) => $query->where('data', 'like', '%' . $request->input('term') . '%')
                )
                ->paginate(50),
        ];
    }
}
