<?php

namespace App\Http\Controllers;

use App\Models\Destino;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;

class DestinoController extends Controller
{
    public function index(): JsonResponse
    {
        $destinos = Destino::activos()->get();
        return response()->json(['data' => $destinos], JsonResponse::HTTP_OK);
    }

    public function store(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'codigo' => ['required', 'string', 'max:50', Rule::unique('destinos', 'codigo')],
            'nombre' => ['required', 'string', 'max:255'],
            'direccion' => ['nullable', 'string'],
            'ciudad' => ['nullable', 'string', 'max:100'],
            'estado' => ['nullable', 'string', 'max:100'],
            'activo' => ['boolean'],
        ], [
            'codigo.required' => 'El código es obligatorio.',
            'codigo.unique' => 'Ya existe un destino con este código.',
            'nombre.required' => 'El nombre es obligatorio.',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], JsonResponse::HTTP_UNPROCESSABLE_ENTITY);
        }

        $destino = Destino::create($request->all());
        return response()->json(['data' => $destino], JsonResponse::HTTP_CREATED);
    }

    public function show(Destino $destino): JsonResponse
    {
        return response()->json(['data' => $destino], JsonResponse::HTTP_OK);
    }

    public function update(Request $request, Destino $destino): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'codigo' => [
                'required',
                'string',
                'max:50',
                Rule::unique('destinos', 'codigo')->ignore($destino->id)
            ],
            'nombre' => ['required', 'string', 'max:255'],
            'direccion' => ['nullable', 'string'],
            'ciudad' => ['nullable', 'string', 'max:100'],
            'estado' => ['nullable', 'string', 'max:100'],
            'activo' => ['boolean'],
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], JsonResponse::HTTP_UNPROCESSABLE_ENTITY);
        }

        $destino->update($request->all());
        return response()->json(['data' => $destino], JsonResponse::HTTP_OK);
    }

    public function destroy(Destino $destino): JsonResponse
    {
        $destino->update(['activo' => false]);
        return response()->json(null, JsonResponse::HTTP_NO_CONTENT);
    }
}

