<?php

namespace App\Http\Controllers;

use App\Http\Resources\AuditListResource;
use App\Http\Resources\AuditViewResource;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\Audit;

class AuditController extends Controller
{
    public function index(Request $request): AuditListResource
    {
        $entries = Audit::query()
            ->when(
                $request->filled('user') && $request->input('user') !== 'null',
                fn($query) => $query->where('user_id', $request->input('user'))
            )
            ->when(
                $request->filled('type') && $request->input('type') !== 'All',
                fn($query) => $query->where('auditable_type', $request->input('type'))
            )
            ->when(
                $request->filled('entry') && $request->input('entry') !== 'null',
                fn($query) => $query->where('auditable_id', $request->input('entry'))
            )
            ->with([
                'user',
                'auditable',
            ])
            ->setSortBy($request->input('sort_by'))
            ->paginate();
        return new AuditListResource($entries);
    }

    public function show(Audit $audit): AuditViewResource
    {
        return new AuditViewResource($audit);
    }
}
