<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Size;
use Illuminate\Http\Request;
class SizeController extends Controller
{
    public function index(Request $request)
    {
        $query = Size::query();
        if ($request->has('search')) {
            $query->where('name', 'like', "%{$request->search}%");
        }
        if ($request->has('per_page')) {
            return $query->orderBy('name')->paginate($request->per_page);
        }
        return $query->orderBy('name')->get();
    }
    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => [
                'required',
                \Illuminate\Validation\Rule::unique('sizes')->whereNull('deleted_at'),
            ],
        ]);
        $size = Size::create($data);
        return response()->json($size, 201);
    }
    public function update(Request $request, string $id)
    {
        $size = Size::findOrFail($id);
        $size->update($request->all());
        return response()->json($size);
    }
    public function destroy(string $id)
    {
        $size = Size::findOrFail($id);
        // With Soft Deletes, we can allow deletion even if sub-sizes exist.
        // The sub-sizes remain but parent is effectively archived.
        // If strict cascade is needed, we'd delete them too, but for now just allow parent delete.
        $size->delete();
        return response()->json(['message' => 'Size deleted successfully']);
    }
}
