<?php

namespace PloverCRM\Core\Api\V1;

use PloverCRM\Common\ActivityEventManager;
use PloverCRM\Common\Permissions;
use PloverCRM\Core\Api\AbstractEndpoint;
use WP_REST_Request;

/**
 * Returns structured feature-level activity logs for the app.
 */
class FeatureLogsEndpoint extends AbstractEndpoint
{
    public function getRoute(): string
    {
        return '/feature-logs';
    }

    public function getMethod()
    {
        return 'GET';
    }

    public function checkPermission(WP_REST_Request $request)
    {
        $passwordAuth = $this->authenticateWithPassword($request);

        if ($passwordAuth) {
            wp_set_current_user((int) $passwordAuth['user_id']);
        }

        $accessCheck = Permissions::adminPermissionCheck();
        if ($accessCheck !== true) {
            return $accessCheck;
        }

        if (!Permissions::isSuperAdmin()) {
            return $this->error(
                'Only CRM owners can view feature logs.',
                403,
                'feature_logs_forbidden'
            );
        }

        return true;
    }

    public function handle(WP_REST_Request $request)
    {
        $modules = $request->get_param('modules') ?? $request->get_param('module') ?? [];
        $features = $request->get_param('features') ?? $request->get_param('feature') ?? [];

        if (
            (empty($modules) || (is_string($modules) && trim($modules) === '')) &&
            (empty($features) || (is_string($features) && trim($features) === ''))
        ) {
            return $this->error(
                'A module or feature filter is required.',
                422,
                'feature_logs_missing_filter'
            );
        }

        return $this->success(ActivityEventManager::query([
            'modules' => $modules,
            'features' => $features,
            'levels' => $request->get_param('levels') ?? $request->get_param('level') ?? [],
            'task_id' => $request->get_param('task_id'),
            'before_id' => $request->get_param('before_id'),
            'limit' => $request->get_param('limit'),
        ]));
    }
}
