<?php
/**
 * Menu Overrides API
 *
 * Handles role-based menu overrides CRUD.
 *
 * @package FleekDash
 * @since V2.2
 */

namespace FleekDash\API;

use Throwable;
use WP_REST_Request;
use WP_REST_Response;
use FleekDash\Admin\Menu\MenuOverridesService;
use FleekDash\Core\AuthMiddleware;

class MenuOverridesAPI
{
    private const MSG_NOT_AUTHENTICATED = 'Not authenticated';

    private const MSG_ROLE_REQUIRED = 'Role parameter is required';

    private MenuOverridesService $menuOverrides;

    public function __construct()
    {
        $this->menuOverrides = new MenuOverridesService();
    }

    public function checkPermissions(): bool
    {
        // Always return true - auth handled inside methods with graceful fallback.
        return true;
    }

    public function getRoleOverrides(WP_REST_Request $request): WP_REST_Response
    {
        try {
            $auth = AuthMiddleware::check('authenticated');
            $authorized = !empty($auth['authenticated']);

            if (!$authorized) {
                $response = new WP_REST_Response([
                    'success' => false,
                    'message' => self::MSG_NOT_AUTHENTICATED,
                    'fallback_data' => [],
                ], 200);
            } else {
                $role = $request->get_param('role');
                if (empty($role)) {
                    $response = new WP_REST_Response([
                        'success' => false,
                        'message' => self::MSG_ROLE_REQUIRED,
                        'fallback_data' => [],
                    ], 200);
                } else {
                    $overrides = $this->menuOverrides->getRoleOverrides($role);
                    $response = new WP_REST_Response([
                        'success' => true,
                        'data' => [
                            'role' => $role,
                            'overrides' => $overrides,
                            'count' => is_array($overrides) ? count($overrides) : 0,
                        ],
                    ], 200);
                }
            }

            return $response;
        } catch (Throwable $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to get role overrides',
                'fallback_data' => [],
            ], 200);
        }
    }

    public function saveRoleOverrides(WP_REST_Request $request): WP_REST_Response
    {
        try {
            $auth = AuthMiddleware::check('authenticated');
            $authorized = !empty($auth['authenticated'])
                && AuthMiddleware::validateRestNonceForMutation($request);

            if (!$authorized) {
                $response = new WP_REST_Response([
                    'success' => false,
                    'message' => self::MSG_NOT_AUTHENTICATED,
                    'fallback_data' => [],
                ], 200);
            } else {
                $role = $request->get_param('role');
                $body = json_decode($request->get_body(), true);
                $overrides = is_array($body) ? ($body['overrides'] ?? []) : [];

                if (empty($role)) {
                    $response = new WP_REST_Response([
                        'success' => false,
                        'message' => self::MSG_ROLE_REQUIRED,
                        'fallback_data' => [],
                    ], 200);
                } else {
                    $this->menuOverrides->saveRoleOverrides($role, $overrides);
                    $response = new WP_REST_Response([
                        'success' => true,
                        'message' => 'Role overrides saved',
                        'data' => [
                            'role' => $role,
                            'count' => is_array($overrides) ? count($overrides) : 0,
                        ],
                    ], 200);
                }
            }

            return $response;
        } catch (Throwable $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to save role overrides',
                'fallback_data' => [],
            ], 200);
        }
    }

    public function resetRoleOverrides(WP_REST_Request $request): WP_REST_Response
    {
        try {
            $auth = AuthMiddleware::check('authenticated');
            $authorized = !empty($auth['authenticated'])
                && AuthMiddleware::validateRestNonceForMutation($request);

            if (!$authorized) {
                $response = new WP_REST_Response([
                    'success' => false,
                    'message' => self::MSG_NOT_AUTHENTICATED,
                    'fallback_data' => [],
                ], 200);
            } else {
                $role = $request->get_param('role');
                if (empty($role)) {
                    $response = new WP_REST_Response([
                        'success' => false,
                        'message' => self::MSG_ROLE_REQUIRED,
                        'fallback_data' => [],
                    ], 200);
                } else {
                    $this->menuOverrides->resetRoleOverrides($role);
                    $response = new WP_REST_Response([
                        'success' => true,
                        'message' => 'Role overrides reset successfully',
                        'data' => [
                            'role' => $role,
                        ],
                    ], 200);
                }
            }

            return $response;
        } catch (Throwable $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to reset role overrides',
                'fallback_data' => [],
            ], 200);
        }
    }
}
