<?php

namespace App\Http\Middleware;

use App\Models\Product;
use App\Models\Purchase;
use App\Models\RawMaterial;
use Closure;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Symfony\Component\HttpFoundation\Response;

class EnsureNoPendingOwnerVerification
{
    public function handle(Request $request, Closure $next, string $routeParameter): Response
    {
        $subject = $request->route($routeParameter);

        if (! $subject instanceof Product && ! $subject instanceof RawMaterial && ! $subject instanceof Purchase) {
            return $next($request);
        }

        if (! $subject->hasPendingOwnerVerification()) {
            return $next($request);
        }

        $label = match ($subject::class) {
            Product::class => 'Produk',
            RawMaterial::class => 'Bahan baku',
            Purchase::class => 'Belanja',
            default => 'Data',
        };

        $redirectRoute = match ($subject::class) {
            Product::class => route('admin.master.products.index'),
            RawMaterial::class => route('admin.master.raw_materials.index'),
            Purchase::class => route('admin.manage.purchases.index'),
            default => route('admin.dashboard'),
        };

        Inertia::flash('error', "{$label} sedang menunggu verifikasi owner.");

        return redirect($redirectRoute);
    }
}
