<?php

namespace App\Http\Controllers\Administracion\Crud;

use App\Http\Controllers\Controller;
use App\Services\Administracion\Crud\CrudEntityService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;

abstract class BaseCrudController extends Controller
{
    public function __construct(
        protected readonly CrudEntityService $crudService,
    ) {
    }

    public function index(Request $request): View|RedirectResponse
    {
        $data = $this->crudService->buildIndexData($request);
        if ($data instanceof RedirectResponse) {
            return $data;
        }

        $entityView = $this->crudService->listViewName();
        if (view()->exists($entityView)) {
            return view($entityView, $data);
        }

        return view('administracion.crud.list', $data);
    }

    public function create(): View|RedirectResponse
    {
        if ($redirect = $this->crudService->guardWritableRedirect()) {
            return $redirect;
        }

        return view('administracion.crud.form', $this->crudService->buildFormData());
    }

    public function importForm(): View|RedirectResponse
    {
        if ($redirect = $this->crudService->guardWritableRedirect()) {
            return $redirect;
        }

        return view('administracion.crud.import', $this->crudService->buildImportFormData());
    }

    public function importTemplate(): StreamedResponse
    {
        abort_if($this->crudService->isReadOnly(), 403);

        return $this->crudService->downloadImportTemplate();
    }

    public function importStore(Request $request): RedirectResponse
    {
        return $this->crudService->import($request);
    }

    public function store(Request $request): RedirectResponse
    {
        return $this->crudService->store($request);
    }

    public function edit(int $id): View|RedirectResponse
    {
        if ($redirect = $this->crudService->guardWritableRedirect()) {
            return $redirect;
        }

        return view('administracion.crud.form', $this->crudService->buildFormData($id));
    }

    public function update(Request $request, int $id): RedirectResponse
    {
        return $this->crudService->update($request, $id);
    }

    public function destroy(int $id): RedirectResponse
    {
        return $this->crudService->destroy($id);
    }
}