<?php

namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Exception;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;

class PasswordController extends Controller
{
    public function changePassword(Request $request)
    {
        $validatedData = Validator::make($request->all(), [
            'current_password' => 'required|string',
            'new_password' => 'required|string|min:8|confirmed',
        ], [
            'current_password.required' => 'La :attribute es obligatoria.',
            'new_password.required' => 'La :attribute es obligatoria.',
            'new_password.min' => 'La :attribute debe tener al menos :min caracteres.',
            'new_password.confirmed' => 'La confirmación de la :attribute no coincide.',
        ], [
            'current_password' => 'contraseña actual',
            'new_password' => 'nueva contraseña',
        ]);
        if ($validatedData->fails()) {
            return response()->json(['error' => $validatedData->errors()->toArray()], 400);
        }
        try {
            $user = $request->user();
            if (!Hash::check($request->current_password, $user->password)) {
                return response()->json(['error' => "La contraseña actual es incorrecta."], 500);
            }
            $user->password = Hash::make($request->new_password);
            $user->save();
            return response()->json([
                'message' => "Contraseña cambiada con éxito",
            ], Response::HTTP_OK);
        } catch (Exception $ex) {
            return response()->json(['error' => "Ocurrio un error inesperado al intentar autenticar."], 500);
        }
    }
}