<?php
// DESCRIPTION: REST API endpoints for checking whether the service account has access
// to a Google Spreadsheet and retrieving the service account email address.

namespace SheetWise\Api;

use SheetWise\Admin\GoogleSheet;
use WP_REST_Server;

class SheetPermissions extends Swise_REST_Controller {

	/**
	 * Route name
	 *
	 * @since 2.0.0
	 *
	 * @var string
	 */
	protected $base = 'sheet-permissions';

	/**
	 * Register routes
	 *
	 * @since 2.0.0
	 *
	 * @return void
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/' . $this->base . '/check/(?P<id>[\w-]+)',
			[
				[
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => [ $this, 'check_access' ],
					'permission_callback' => [ $this, 'permission_check' ],
				],
			]
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->base . '/service-account',
			[
				[
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => [ $this, 'get_service_account' ],
					'permission_callback' => [ $this, 'permission_check' ],
				],
			]
		);
	}

	/**
	 * Check if the service account has access to a spreadsheet
	 *
	 * @since 2.0.0
	 *
	 * @param \WP_REST_Request $request
	 *
	 * @return \WP_REST_Response
	 */
	public function check_access( $request ) {
		$spreadsheet_id = sanitize_text_field( $request->get_param( 'id' ) );

		$sheet  = new GoogleSheet();
		$result = $sheet->check_sheet_access( $spreadsheet_id );

		return rest_ensure_response( [
			'code'    => 200,
			'success' => true,
			'data'    => $result,
		] );
	}

	/**
	 * Get the service account email
	 *
	 * @since 2.0.0
	 *
	 * @param \WP_REST_Request $request
	 *
	 * @return \WP_REST_Response
	 */
	public function get_service_account( $request ) {
		$email = GoogleSheet::get_service_account_email();

		return rest_ensure_response( [
			'code'    => 200,
			'success' => true,
			'data'    => [
				'email' => $email ?? '',
			],
		] );
	}
}
