<?php

namespace Licenzo\Http\Controller\Api\V1;

use Licenzo\Framework\Http\Request;
use Licenzo\Http\Traits\HandlesErrors;
use Licenzo\Services\SettingsPluginDependencyService;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class SettingsPluginDependencyController
{
    use HandlesErrors;

    /**
     * @var SettingsPluginDependencyService
     */
    private $service;

    public function __construct(?SettingsPluginDependencyService $service = null)
    {
        $this->service = $service ?? new SettingsPluginDependencyService();
    }

    public function status(Request $request)
    {
        $settingsKey = $this->sanitizeSettingsKey($request->getSafe('settings_key', 'sanitize_key', ''));
        if ($settingsKey === '') {
            return $this->validationError(['settings_key' => 'settings_key is required']);
        }

        try {
            $status = $this->service->getStatusForSettingsKey($settingsKey);

            return $this->successResponse($status, 'Plugin dependency status retrieved successfully');
        } catch (\InvalidArgumentException $e) {
            return $this->validationError(['settings_key' => $e->getMessage()], 'Invalid settings dependency key');
        } catch (\Throwable $e) {
            return $this->handleError($e, 'Failed to retrieve plugin dependency status');
        }
    }

    public function ensure(Request $request)
    {
        $settingsKey = $this->sanitizeSettingsKey($request->getSafe('settings_key', 'sanitize_key', ''));
        if ($settingsKey === '') {
            return $this->validationError(['settings_key' => 'settings_key is required']);
        }

        try {
            $result = $this->service->ensureReadyForSettingsKey($settingsKey);

            return $this->successResponse($result, 'Plugin dependencies are ready');
        } catch (\InvalidArgumentException $e) {
            return $this->validationError(['settings_key' => $e->getMessage()], 'Invalid settings dependency key');
        } catch (\Throwable $e) {
            return $this->handleError($e, 'Failed to install/activate required plugins');
        }
    }

    private function sanitizeSettingsKey(string $settingsKey): string
    {
        return sanitize_key($settingsKey);
    }
}
