<?php

namespace FleekDash\API;

use FleekDash\Services\Gmail as GmailService;
use WP_REST_Response;
use WP_Error;
use Exception;

class GmailEndpoints
{
    public function register_routes()
    {
        \register_rest_route('fleekdash/v1', '/gmail/messages', [
            'methods' => 'GET',
            'callback' => [$this, 'list_messages'],
            'permission_callback' => function () {
                return \current_user_can('manage_options');
            }
        ]);

        \register_rest_route('fleekdash/v1', '/gmail/messages/(?P<id>[a-zA-Z0-9]+)', [
            'methods' => 'GET',
            'callback' => [$this, 'get_message'],
            'permission_callback' => function () {
                return \current_user_can('manage_options');
            },
            'args' => [
                'id' => [
                    'required' => true,
                    'type' => 'string',
                    'validate_callback' => function ($param) {
                        return !empty($param);
                    }
                ]
            ]
        ]);

        \register_rest_route('fleekdash/v1', '/gmail/disconnect', [
            'methods' => 'POST',
            'callback' => [$this, 'disconnect'],
            'permission_callback' => function () {
                return \current_user_can('manage_options');
            }
        ]);
    }

    public function list_messages($request)
    {
        try {
            $gmail = new GmailService();
            $query = $request->get_param('q');
            $max_results = $request->get_param('max_results') ?? 20;

            $messages = $gmail->list_messages($max_results, $query);
            return new WP_REST_Response($messages, 200);
        } catch (\Exception $e) {
            return new WP_Error(
                'gmail_error',
                $e->getMessage(),
                ['status' => 500],
            );
        }
    }

    public function get_message($request)
    {
        try {
            $gmail = new GmailService();
            $message_id = $request->get_param('id');

            $message = $gmail->get_message($message_id);
            return new WP_REST_Response($message, 200);
        } catch (\Exception $e) {
            return new WP_Error(
                'gmail_error',
                $e->getMessage(),
                ['status' => 500],
            );
        }
    }

    public function disconnect()
    {
        try {
            $user_id = \get_current_user_id();
            \delete_user_meta($user_id, 'fleekdash_gmail_token');

            return new WP_REST_Response([
                'status' => 'success',
                'message' => 'Gmail disconnected successfully'
            ], 200);
        } catch (\Exception $e) {
            return new WP_Error(
                'gmail_error',
                $e->getMessage(),
                ['status' => 500],
            );
        }
    }
}
