<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\SizeRequest;
use App\Models\Size;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class SizeController extends Controller
{
    public function index(): View
    {
        $sizes = Size::withCount('variants')->orderBy('sort_order')->orderBy('name')->paginate(20);

        return view('admin.sizes.index', compact('sizes'));
    }

    public function store(SizeRequest $request): RedirectResponse
    {
        Size::create($request->validated());

        return back()->with('success', 'Size added.');
    }

    public function update(SizeRequest $request, Size $size): RedirectResponse
    {
        $size->update($request->validated());

        return back()->with('success', 'Size updated.');
    }

    public function destroy(Size $size): RedirectResponse
    {
        if ($size->variants()->exists()) {
            return back()->with('error', 'This size is used by existing product variants.');
        }

        $size->delete();

        return back()->with('success', 'Size deleted.');
    }
}
