<?php

use App\Models\User;
use Illuminate\Contracts\Cache\Repository as CacheRepository;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * Filament path
 *
 * @throws \Symfony\Component\HttpKernel\Exception\HttpException
 */
function filament_path(): string
{
    $path = config()->string('app.filament_path');

    abort_if(! $path, 500, 'Filament path missing');

    return $path;
}

/**
 * Temprory cache for single request
 *
 * @return ($key is '' ? CacheRepository : mixed)
 */
function temp_cache(string $key = ''): mixed
{
    $tempCache = cache()->driver('array');

    return ($key === '') ? $tempCache : $tempCache->get($key);
}

/**
 * Log
 */
function logDB(): void
{
    if (! app()->isLocal()) {
        return;
    }

    DB::listen(function ($query) {
        Log::info($query->sql, $query->bindings, $query->time);
    });
}

/**
 * User
 */
function user(): User
{
    abort_unless(Auth::check(), 401, 'Unauthorized');

    /** @var \App\Models\User */
    $user = Auth::user();

    return $user;
}
