<?php

namespace WeDevs\AppBridge\Core\REST\Auth;

use Exception;
use WeDevs\AppBridge\Core\Auth\SocialLogin;
use WeDevs\AppBridge\Core\Auth\JwtAuth;
use WeDevs\AppBridge\Core\REST\BaseController;
use WP_Error;
use WP_REST_Server;
use WP_REST_Response;
use WP_REST_Request;

class AuthController extends BaseController {
	protected $rest_base = 'auth';

	/**
	 *
	 * @var JwtAuth
	 */
	protected $jwt_auth;

	protected $expires_at;

	protected $expires_in = ( DAY_IN_SECONDS * 7 ); // 1 hour

	public function __construct() {
		$this->jwt_auth = new JwtAuth();

		if ( ! class_exists( 'Jwt_Auth_Public' ) ) {
			add_filter( 'rest_pre_dispatch', [ $this->jwt_auth, 'rest_pre_dispatch' ] );
			add_filter( 'determine_current_user', [ $this->jwt_auth, 'determine_current_user' ] );
		}
	}

	public function register_routes(): void {
		if ( ! $this->jwt_auth ) {
			return;
		}

		register_rest_route(
            $this->namespace, $this->rest_base . '/token', [
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => [ $this->jwt_auth, 'generate_token_for_request' ],
				'permission_callback' => '__return_true',
			]
        );

		register_rest_route(
            $this->namespace, $this->rest_base . '/token/validate', [
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => [ $this->jwt_auth, 'validate_token_for_request' ],
				'permission_callback' => '__return_true',
			]
        );

		register_rest_route(
            $this->namespace, '/' . $this->rest_base . '/social-login', array(
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'social_login' ),
					'permission_callback' => '__return_true',
					'args'                => array(
						'provider'  => array(
							'required'    => true,
							'type'        => 'string',
							'enum'        => array( 'facebook', 'google', 'apple', 'linkedin', 'twitter' ),
							'description' => __( 'Social login provider service like Facebook, Google etc.', 'app-bridge' ),
						),
						'access_token' => array(
							'required'    => true,
							'type'        => 'string',
							'description' => __( 'Access token from social login', 'app-bridge' ),
						),
					),
				),
            )
        );
	}

	/**
     * Social login with Dokan App
     *
     * @since 1.0.0
     *
     * @param WP_REST_Request $request
     *
     * @return WP_REST_Response|WP_Error
     */
    public function social_login( $request ) {
		$params = $request->get_params();
        try {
            $provider     = $params['provider'];
            $access_token = $params['access_token'];

            $social_login = SocialLogin::instance();

            $wp_user = $social_login->get_wp_user( $provider, $access_token );

            if ( is_wp_error( $wp_user ) ) {
                return new WP_Error( 'app_bridge_rest_error', $wp_user->get_error_message(), array( 'status' => 400 ) );
            }

            $auth_service = new JwtAuth();

            $data = $auth_service->generate_token_for_user( $wp_user );

            return rest_ensure_response( $data );
        } catch ( Exception $e ) {
            return new WP_Error( 'app_bridge_rest_error', __( 'Could not authenticate social login', 'app-bridge' ) );
        }
    }
}
