<?php

namespace Tricks\LaravelTools\Nova;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Laravel\Nova\Http\Requests\NovaRequest;
use Laravel\Nova\Resource as NovaResource;

/**
 * @template TModel of Model
 *
 * @mixin TModel
 *
 * @extends NovaResource<TModel>
 */
abstract class Resource extends NovaResource
{
    /** @var class-string<TModel> */
    public static $model;

    /** @var array<string,string> */
    public static array $indexDefaultOrder = [
        'id' => 'desc',
    ];

    /**
     * @param  Builder<Model>  $query
     * @return Builder<Model>
     */
    public static function indexQuery(NovaRequest $request, $query): Builder
    {
        if (empty($request->get('orderBy'))) {
            $query->getQuery()->orders = [];
            $key = key(static::$indexDefaultOrder);
            $value = reset(static::$indexDefaultOrder);
            if ($key && $value) {
                return $query->orderBy($key, $value);
            }
        }

        return $query;
    }

    /**
     * @param  Builder<TModel>  $query
     * @return Builder<TModel>
     */
    public static function detailQuery(NovaRequest $request, $query): Builder
    {
        return parent::detailQuery($request, $query);
    }

    /**
     * @param  Builder<TModel>  $query
     * @return Builder<TModel>
     */
    public static function relatableQuery(NovaRequest $request, $query): Builder
    {
        return parent::relatableQuery($request, $query);
    }

    /**
     * @param  NovaResource<TModel>  $resource
     */
    public static function redirectAfterCreate(NovaRequest $request, $resource): string
    {
        return '/resources/'.static::uriKey();
    }

    /**
     * @param  NovaResource<TModel>  $resource
     */
    public static function redirectAfterUpdate(NovaRequest $request, $resource): string
    {
        return '/resources/'.static::uriKey();
    }
}
