<?php

namespace App\Http\Controllers\Api;

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

class BrandController extends Controller
{
    public function index(Request $request)
    {
        if ($request->has('per_page')) {
            return Brand::latest()->paginate($request->per_page);
        }
        return Brand::latest()->get();
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => [
                'required',
                'string',
                'max:255',
                \Illuminate\Validation\Rule::unique('brands')->whereNull('deleted_at'),
            ],
        ]);

        return Brand::create($data);
    }

    public function update(Request $request, Brand $brand)
    {
        $data = $request->validate([
            'name' => [
                'required',
                'string',
                'max:255',
                \Illuminate\Validation\Rule::unique('brands')->whereNull('deleted_at')->ignore($brand->id),
            ],
            'is_active' => 'boolean'
        ]);

        $brand->update($data);
        return $brand;
    }

    public function destroy(Brand $brand)
    {
        $brand->delete();
        return response()->noContent();
    }
}
