<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreLaundrySaleCategoryRequest;
use App\Http\Requests\UpdateLaundrySaleCategoryRequest;
use App\Http\Controllers\Concerns\DestroysCatalogItem;
use App\Models\LaundrySaleCategory;
use App\Support\CatalogDeletionGuard;
use App\Support\CatalogCodeGenerator;
use Illuminate\Http\JsonResponse;

class LaundrySaleCategoryAdminController extends Controller
{
    use DestroysCatalogItem;
    public function index(): JsonResponse
    {
        $this->authorize('viewAny', LaundrySaleCategory::class);

        $rows = LaundrySaleCategory::query()->orderBy('sort_order')->orderBy('id')->get();

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

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

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

    public function update(UpdateLaundrySaleCategoryRequest $request, LaundrySaleCategory $laundrySaleCategory): JsonResponse
    {
        $laundrySaleCategory->fill($request->validated());
        $laundrySaleCategory->save();

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

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

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

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

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