<?php

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;

abstract class Controller
{
    protected function handleAction(callable $action, string $successMessage, string $redirectRoute, ?string $errorRoute = null, array $parameters = []): RedirectResponse
    {
        try {
            $action();
            Inertia::flash('toast', ['type' => 'success', 'message' => $successMessage]);

            return to_route($redirectRoute, $parameters);
        } catch (ValidationException $e) {
            $firstError = collect($e->errors())->flatten()->first();
            Inertia::flash('toast', ['type' => 'error', 'message' => $firstError ?? 'Terjadi kesalahan.']);

            return to_route($errorRoute ?? $redirectRoute, $parameters);
        } catch (\Exception $e) {
            Log::error($e->getMessage(), ['exception' => $e]);
            Inertia::flash('toast', ['type' => 'error', 'message' => 'Terjadi kesalahan. Silakan coba lagi.']);

            return to_route($errorRoute ?? $redirectRoute, $parameters);
        }
    }

    protected function handleToggle(callable $action, string $successMessage, string $redirectRoute): RedirectResponse
    {
        return $this->handleAction($action, $successMessage, $redirectRoute);
    }
}
