<?php

namespace App\Http\Controllers\Api\V1\Product;

use App\Http\Controllers\Controller;
use App\Models\CupSize;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CupSizeController extends Controller
{
    /**
     * Get all cup sizes
     */
    public function index(): JsonResponse
    {
        $cupSizes = CupSize::active()->ordered()->get();

        return response()->json([
            'data' => $cupSizes
        ]);
    }

    /**
     * Get a specific cup size
     */
    public function show(int $id): JsonResponse
    {
        $cupSize = CupSize::findOrFail($id);

        return response()->json([
            'data' => $cupSize
        ]);
    }

    /**
     * Create a new cup size (admin only)
     */
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:cup_sizes,code',
            'scoop_count' => 'required|integer|min:1',
            'weight_grams' => 'required|numeric|min:0',
            'price' => 'nullable|numeric|min:0',
            'description' => 'nullable|string',
            'display_order' => 'nullable|integer',
        ]);

        $cupSize = CupSize::create($validated);

        return response()->json([
            'data' => $cupSize,
            'message' => 'Cup size created successfully'
        ], 201);
    }

    /**
     * Update a cup size (admin only)
     */
    public function update(Request $request, int $id): JsonResponse
    {
        $cupSize = CupSize::findOrFail($id);

        $validated = $request->validate([
            'name' => 'sometimes|string|max:255',
            'code' => 'sometimes|string|max:50|unique:cup_sizes,code,' . $id,
            'scoop_count' => 'sometimes|integer|min:1',
            'weight_grams' => 'sometimes|numeric|min:0',
            'price' => 'nullable|numeric|min:0',
            'description' => 'nullable|string',
            'is_active' => 'sometimes|boolean',
            'display_order' => 'nullable|integer',
        ]);

        $cupSize->update($validated);

        return response()->json([
            'data' => $cupSize,
            'message' => 'Cup size updated successfully'
        ]);
    }

    /**
     * Delete a cup size (admin only)
     */
    public function destroy(int $id): JsonResponse
    {
        $cupSize = CupSize::findOrFail($id);
        $cupSize->delete();

        return response()->json([
            'message' => 'Cup size deleted successfully'
        ]);
    }
}
