<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AssetCategory;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class AssetCategoryController extends Controller
{
    public function index(): Response
    {
        return Inertia::render('Admin/Assets/Categories', [
            'categories' => AssetCategory::withCount('assets')->get(),
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:asset_categories,name',
            'description' => 'nullable|string',
        ]);

        AssetCategory::create($validated);

        return back()->with('success', 'Asset category created successfully.');
    }

    public function update(Request $request, AssetCategory $assetCategory)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:asset_categories,name,'.$assetCategory->id,
            'description' => 'nullable|string',
        ]);

        $assetCategory->update($validated);

        return back()->with('success', 'Asset category updated successfully.');
    }

    public function destroy(AssetCategory $assetCategory)
    {
        if ($assetCategory->assets()->exists()) {
            return back()->with('error', 'Cannot delete category with associated assets.');
        }

        $assetCategory->delete();

        return back()->with('success', 'Asset category deleted successfully.');
    }
}
