<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Concerns\DestroysCatalogItem;
use App\Http\Requests\StoreClienteCategoriaRequest;
use App\Http\Requests\UpdateClienteCategoriaRequest;
use App\Models\ClienteCategoria;
use App\Support\CatalogCodeGenerator;
use App\Support\CatalogDeletionGuard;
use Illuminate\Http\JsonResponse;

class ClienteCategoriaAdminController extends Controller
{
    use DestroysCatalogItem;

    public function index(): JsonResponse
    {
        $this->authorize('viewAny', ClienteCategoria::class);

        $rows = ClienteCategoria::query()
            ->withCount('clientes')
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();

        return response()->json([
            'data' => $rows,
            'meta' => null,
            'errors' => null,
        ], JsonResponse::HTTP_OK);
    }

    public function store(StoreClienteCategoriaRequest $request): JsonResponse
    {
        $data = $request->validated();
        $categoria = ClienteCategoria::query()->create([
            'code' => CatalogCodeGenerator::resolve(
                $data['code'] ?? null,
                $data['name'],
                ClienteCategoria::class,
                'code',
                'cliente',
            ),
            'name' => $data['name'],
            'color' => $data['color'] ?? null,
            'sort_order' => $data['sort_order'] ?? 0,
            'is_active' => $data['is_active'] ?? true,
        ]);

        return response()->json([
            'data' => $categoria,
            'meta' => null,
            'errors' => null,
        ], JsonResponse::HTTP_CREATED);
    }

    public function update(UpdateClienteCategoriaRequest $request, ClienteCategoria $clienteCategoria): JsonResponse
    {
        $clienteCategoria->fill($request->validated());
        $clienteCategoria->save();

        return response()->json([
            'data' => $clienteCategoria->fresh()->loadCount('clientes'),
            'meta' => null,
            'errors' => null,
        ], JsonResponse::HTTP_OK);
    }

    public function disable(ClienteCategoria $clienteCategoria): JsonResponse
    {
        $this->authorize('update', $clienteCategoria);
        $clienteCategoria->is_active = false;
        $clienteCategoria->save();

        return response()->json([
            'data' => $clienteCategoria->fresh()->loadCount('clientes'),
            'meta' => null,
            'errors' => null,
        ], JsonResponse::HTTP_OK);
    }

    public function destroy(ClienteCategoria $clienteCategoria): JsonResponse
    {
        $this->authorize('delete', $clienteCategoria);

        return $this->destroyCatalogItem(
            CatalogDeletionGuard::clienteCategoria($clienteCategoria),
            fn () => $clienteCategoria->delete(),
        );
    }
}
