<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Size;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class SizeController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $sizes = Size::all();
        return response()->json($sizes);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {
            $request->validate([
                'size_name' => 'required|string|max:20|unique:sizes,size_name',
                'active_status' => 'int',
            ]);

            $size = Size::create($request->all());
            return response()->json($size, 201);
        } catch (ValidationException $e) {
            return response()->json(['errors' => $e->errors()], 422);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Error creating size', 'error' => $e->getMessage()], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(Size $size)
    {
        return response()->json($size);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Size $size)
    {
        try {
            $request->validate([
                'size_name' => 'sometimes|required|string|max:20|unique:sizes,size_name,' . $size->size_id . ',size_id',
                'active_status' => 'sometimes|boolean',
            ]);

            $size->update($request->all());
            return response()->json($size);
        } catch (ValidationException $e) {
            return response()->json(['errors' => $e->errors()], 422);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Error updating size', 'error' => $e->getMessage()], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Size $size)
    {
        try {
            $size->delete();
            return response()->json(['message' => 'Size deleted successfully'], 204);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Error deleting size', 'error' => $e->getMessage()], 500);
        }
    }
}
