<?php
namespace Bookaro\Controller\Rest;

defined( 'ABSPATH' ) || exit;

use Bookaro\Service\PrivacyService;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

class UserDataController extends BaseController
{
    private PrivacyService $privacyService;

    public function __construct( PrivacyService $privacyService )
    {
        $this->privacyService = $privacyService;
    }

    public function register_routes(): void
    {
        register_rest_route( $this->namespace, '/personal-data', [
            'methods'             => WP_REST_Server::DELETABLE,
            'callback'            => [ $this, 'delete_personal_data' ],
            'permission_callback' => [ $this, 'can_delete_personal_data' ],
            'description'         => __( 'Delete personal data for current user. Returns WP_Error on failure.', 'mybookaro' ),
        ] );
    }

    public function can_delete_personal_data( WP_REST_Request $req ): bool|WP_Error
    {
        return $this->require_authenticated_write(
            $req,
            __( 'You must be logged in to delete personal data.', 'mybookaro' )
        );
    }

    public function delete_personal_data( WP_REST_Request $req ): WP_REST_Response|WP_Error
    {
        $user_id = get_current_user_id();

        try {
            $this->privacyService->delete_user_data( $user_id );
        } catch ( \Throwable $e ) {
            return new WP_Error( 'privacy_data_delete_failed', $e->getMessage(), [ 'status' => 500 ] );
        }

        wp_logout();

        return rest_ensure_response( [ 'success' => true ] );
    }
}
