<?php

namespace App\Services\Administracion\Crud;

use App\Models\TipoInsumo;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class TiposInsumosCrudService extends CrudEntityService
{
    protected string $entity = 'tipos-insumos';

    protected string $modelClass = TipoInsumo::class;

    protected array $entityLabels = [
        'singular' => 'Tipo de Bien',
        'plural' => 'Tipos de Bien',
        'create' => 'Nuevo Tipo de Bien',
    ];

    protected array $tableColumns = ['nombre'];

    protected array $tableLabels = ['nombre' => 'Nombre'];

    protected array $formLabels = ['nombre' => 'Nombre'];

    protected array $searchColumns = ['nombre'];

    protected ?string $searchPlaceholder = 'Buscar por nombre del tipo de bien';

    protected array $editableColumns = ['nombre'];

    protected array $importLookupColumns = ['nombre'];

    protected ?array $defaultSort = ['nombre', 'asc'];

    protected function buildStoreRedirect(Request $request, Model $record): RedirectResponse
    {
        $returnEntity = trim((string) $request->input('__return_entity', ''));
        $returnUrl = trim((string) $request->input('__return_url', ''));
        $restoreDraftKey = trim((string) $request->input('__restore_draft_key', ''));

        if ($returnEntity === 'bienes') {
            $query = ['open_modal' => 'create', 'selected_tipo' => (string) $record->getKey()];
            if ($restoreDraftKey !== '') {
                $query['restore_draft_key'] = $restoreDraftKey;
            }

            $safeReturnUrl = $this->normalizeCrudReturnUrl($returnUrl, $returnEntity);
            if ($safeReturnUrl !== null) {
                return redirect()
                    ->to($this->appendQueryToRelativeUrl($safeReturnUrl, $query))
                    ->with('status', 'Tipo de bien creado.');
            }

            return redirect()
                ->route('administracion.crud.index', array_merge(['entity' => $returnEntity], $query))
                ->with('status', 'Tipo de bien creado.');
        }

        return parent::buildStoreRedirect($request, $record);
    }
}