<?php

namespace App\Http\Controllers\Api;

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

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

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

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

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Brand $brand)
    {
        try {
            $request->validate([
                'brand_name' => 'sometimes|required|string|max:100|unique:brands,brand_name,' . $brand->brand_id . ',brand_id',
                'active_status' => 'sometimes|boolean',
            ]);

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

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