<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\DepartmentRequest;
use App\Http\Requests\IndexQueryRequest;
use App\Http\Resources\DepartmentResource;
use App\Models\Department;
use Illuminate\Database\QueryException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DepartmentController extends Controller
{

    private array $messages = [
        'index'          => 'Lista de Departamentos obtenidos exitosamente',
        'store'          => 'Departamento creado exitosamente',
        'show'           => 'Departamento obtenido exitosamente',
        'update'         => 'Departamento actualizado exitosamente',
        'destroy'        => 'Departamento eliminado exitosamente',
        'not_found'      => 'Departamento no encontrado',
        'cannot_destroy' => 'No se puede eliminar el Departamento porque tiene provincias asignadas',
    ];

    public function index(IndexQueryRequest $request): JsonResponse
    {
        $items = Department::query()
            ->included()
            ->search()
            ->filter()
            ->sort()
            ->paginated();

        return DepartmentResource::collection($items)
            ->additional([
                'success' => true,
                'message' => $this->messages['index']
            ])
            ->response();
    }

    public function store(DepartmentRequest $request): JsonResponse
    {
        $item = Department::create($request->validated());

        return DepartmentResource::make($item)
            ->additional([
                'success' => true,
                'message' => $this->messages['store']
            ])
            ->response()
            ->setStatusCode(201);
    }

    public function show(int $id): JsonResponse
    {
        $item = Department::findOrAbort($id, $this->messages['not_found']);

        return DepartmentResource::make($item)
            ->additional([
                'success' => true,
                'message' => $this->messages['show']
            ])
            ->response();
    }

    public function update(DepartmentRequest $request, int $id): JsonResponse
    {
        $item = Department::findOrAbort($id, $this->messages['not_found']);
        $item->update($request->validated());

        return DepartmentResource::make($item)
            ->additional([
                'success' => true,
                'message' => $this->messages['update']
            ])
            ->response();
    }

    public function destroy(int $id): JsonResponse
    {
        try {
            $item = Department::findOrAbort($id, $this->messages['not_found']);
            $item->delete();

            return DepartmentResource::make($item)
                ->additional([
                    'success' => true,
                    'message' => $this->messages['destroy']
                ])
                ->response();
        } catch (QueryException $e) {
            // Foreign key constraint violation
            if ($e->getCode() === '23000') {
                return response()->json([
                    'success' => false,
                    'message' => $this->messages['cannot_destroy']
                ], 409);
            }

            // Re-lanzar otros errores para que el handler global los maneje
            throw $e;
        }
    }
}
