<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreBrandRequest;
use App\Http\Resources\BrandResource;
use App\Models\Brand;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class BrandController extends Controller
{
    /**
     * Display a listing of brands.
     */
    public function index(Request $request): AnonymousResourceCollection
    {
        $query = Brand::query()->ordered();

        // Filter by active status
        if ($request->has('active')) {
            $query->where('active', filter_var($request->active, FILTER_VALIDATE_BOOLEAN));
        }

        // Include products if requested
        if ($request->has('with_products')) {
            $query->with(['products' => function ($q) use ($request) {
                if ($request->has('active_products_only')) {
                    $q->where('active', true);
                }
            }]);
        }

        $brands = $query->get();

        return BrandResource::collection($brands);
    }

    /**
     * Store a newly created brand.
     */
    public function store(StoreBrandRequest $request): JsonResponse
    {
        $brand = Brand::create($request->validated());

        return response()->json([
            'success' => true,
            'message' => 'Brand created successfully.',
            'data' => new BrandResource($brand),
        ], 201);
    }

    /**
     * Display the specified brand.
     */
    public function show(Request $request, Brand $brand): JsonResponse
    {
        // Load products if requested
        if ($request->has('with_products')) {
            $brand->load(['products' => function ($q) use ($request) {
                if ($request->has('active_products_only')) {
                    $q->where('active', true);
                }
            }]);
        }

        return response()->json([
            'success' => true,
            'data' => new BrandResource($brand),
        ]);
    }

    /**
     * Update the specified brand.
     */
    public function update(Request $request, Brand $brand): JsonResponse
    {
        $validated = $request->validate([
            'name' => ['sometimes', 'string', 'max:255', 'unique:brands,name,' . $brand->id],
            'active' => ['sometimes', 'boolean'],
            'sort_order' => ['sometimes', 'integer', 'min:0'],
        ]);

        $brand->update($validated);

        return response()->json([
            'success' => true,
            'message' => 'Brand updated successfully.',
            'data' => new BrandResource($brand),
        ]);
    }

    /**
     * Remove the specified brand.
     */
    public function destroy(Brand $brand): JsonResponse
    {
        $brand->delete();

        return response()->json([
            'success' => true,
            'message' => 'Brand deleted successfully.',
        ]);
    }
}
