<?php

namespace App\Http\Controllers\API;

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

class BrandController extends Controller
{
    public function index(Request $request)
    {
        $query = Brand::withCount('products');

        if ($request->filled('search')) {
            $query->where('name', 'like', "%{$request->search}%");
        }

        if ($request->filled('is_active')) {
            $query->where('is_active', filter_var($request->is_active, FILTER_VALIDATE_BOOLEAN));
        }

        $brands = $query->orderBy('name')
            ->paginate($request->get('per_page', 50));

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name'        => 'required|string|max:255|unique:brands,name',
            'description' => 'nullable|string',
            'website'     => 'nullable|url|max:255',
            'is_active'   => 'boolean',
        ]);

        $validated['slug'] = $this->uniqueSlug(Str::slug($validated['name']));
        $brand = Brand::create($validated);

        return response()->json([
            'success' => true,
            'message' => 'Marca criada com sucesso',
            'data'    => $brand,
        ], 201);
    }

    public function update(Request $request, $id)
    {
        $brand = Brand::findOrFail($id);

        $validated = $request->validate([
            'name'        => 'sometimes|string|max:255|unique:brands,name,' . $id,
            'description' => 'nullable|string',
            'website'     => 'nullable|url|max:255',
            'is_active'   => 'boolean',
        ]);

        if (isset($validated['name'])) {
            $validated['slug'] = $this->uniqueSlug(Str::slug($validated['name']), $id);
        }

        $brand->update($validated);

        return response()->json([
            'success' => true,
            'message' => 'Marca actualizada',
            'data'    => $brand->fresh(),
        ]);
    }

    public function destroy($id)
    {
        $brand = Brand::withCount('products')->findOrFail($id);

        if ($brand->products_count > 0) {
            return response()->json([
                'success' => false,
                'message' => "Não é possível eliminar: esta marca tem {$brand->products_count} produto(s) associado(s).",
            ], 422);
        }

        $brand->delete();

        return response()->json(['success' => true, 'message' => 'Marca eliminada']);
    }

    private function uniqueSlug(string $base, ?int $excludeId = null): string
    {
        $slug = $base;
        $n = 1;
        $query = \DB::table('brands')->where('slug', $slug)->whereNull('deleted_at');
        if ($excludeId) $query->where('id', '!=', $excludeId);
        while ($query->clone()->exists()) {
            $slug = $base . '-' . $n++;
            $query = \DB::table('brands')->where('slug', $slug)->whereNull('deleted_at');
            if ($excludeId) $query->where('id', '!=', $excludeId);
        }
        return $slug;
    }
}
