<?php

namespace App\Http\Controllers\Api;

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

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

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

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

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Color $color)
    {
        try {
            $request->validate([
                'color_name' => 'sometimes|required|string|max:100|unique:colors,color_name,' . $color->color_id . ',color_id',
                'active_status' => 'sometimes|boolean',
            ]);

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

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