<?php

namespace Booktics\Abstracts;

if ( ! defined( 'ABSPATH' ) ) exit;

use Booktics\Contracts\Hookable_Service_Contract;
use Exception;
use WP_Error;
use WP_HTTP_Response;
use WP_REST_Controller;

/**
 * BaseRest Controller
 *
 * @package Booktics/Abstracts
 */
abstract class Base_Rest_Controller extends WP_REST_Controller implements Hookable_Service_Contract {
    /**
     * Register routes
     *
     * @return  void
     */
    public function register(): void {
        add_action( 'rest_api_init', array( $this, 'register_routes' ) );
    }

    /**
     * Register all routes
     *
     * @return  void
     */
    public function register_routes(): void {
        throw new Exception( 'Need to override register_routes method from child class' );
    }

    /**
     * Send rest error
     *
     * @param string $message Error message
     * @param integer $status_code Error status code
     *
     * @return  WP_HTTP_Response
     */
    public function error( $message, $status_code = 422, $type = '', $details = '' ) {
        $data = array(
            'success' => 0,
            'message' => $message,
            'error'   => array(
                'code'    => $status_code,
                'type'    => $type,
                'details' => $details,
            ),
        );

        return new WP_HTTP_Response( $data, $status_code );
    }

    /**
     * Send rest response
     *
     * @param array $data Response data
     *
     * @return  WP_HTTP_Response
     */
    public function response( $data, $message = '', $status_code = 200 ) {
        if ( ! $message ) {
            $message = __( 'Request was successful', 'booktics' );
        }

        $data = array(
            'success' => 1,
            'message' => $message,
            'data'    => $data,
        );

        return new WP_HTTP_Response( $data, $status_code );
    }
}
