<?php
/**
 * Error Handling Trait
 *
 * @package Licenzo\Http\Traits
 */

namespace Licenzo\Http\Traits;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Standardized error handling for controllers
 */
trait HandlesErrors
{
    /**
     * Handle exceptions and return standardized error response
     *
     * @param \Throwable $e
     * @param string $defaultMessage
     * @param int $defaultStatus
     * @return array
     */
    protected function handleError(\Throwable $e, string $defaultMessage = 'An error occurred', int $defaultStatus = 500): array
    {
        return [
            'success' => false,
            'message' => $defaultMessage,
            'error'   => defined('WP_DEBUG') && WP_DEBUG ? $e->getMessage() : null,
            'status'  => $defaultStatus
        ];
    }

    /**
     * Return success response
     *
     * @param mixed $data
     * @param string $message
     * @return array
     */
    protected function successResponse($data = null, string $message = 'Operation successful'): array
    {
        $response = [
            'success' => true,
            'message' => $message
        ];

        if ($data !== null) {
            $response['data'] = $data;
        }

        return $response;
    }

    /**
     * Return validation error response
     *
     * @param array $errors
     * @param string $message
     * @return array
     */
    protected function validationError(array $errors = [], string $message = 'Validation failed'): array
    {
        return [
            'success' => false,
            'message' => $message,
            'errors'  => $errors,
            'status'  => 422
        ];
    }

    /**
     * Return not found error response
     *
     * @param string $message
     * @return array
     */
    protected function notFoundError(string $message = 'Resource not found'): array
    {
        return [
            'success' => false,
            'message' => $message,
            'status'  => 404
        ];
    }
}
