<?php
namespace OxygenApp\Common\Guards;

if ( ! defined( 'ABSPATH' ) ) exit;

use WP_REST_Request;
use OxygenApp\Common\Validation\FieldsValidator;
use OxygenApp\Utils\UserUtil;
use OxygenApp\Models\User;
use OxygenApp\Utils\LanguagesHelper;
use OxygenApp\Models\Background;

class UserBackgroundGuard extends BaseGuard implements GuardInterface {

    public static function check(WP_REST_Request $request): array {

        $fieldsRules = [
            [
                'field_name' => 'bid',
                'required' => true,
                'type' => 'int',
                'min_length' => 1,
                'max_length' => 30
            ],
        ];

        $params = $request->get_param('background');

        $validatorResult = FieldsValidator::validate($params, $fieldsRules);

        if (!$validatorResult['status']) {
            return self::getFailedResponse($validatorResult['errorMessage'], 400);
        }

        if (!UserUtil::isLoggedIn()) {
            $background_login_required_err = LanguagesHelper::getInstance()->getLangLabel('background_login_required_err');
            return self::getFailedResponse(esc_html($background_login_required_err), 403);
        }

        $userSessionData = UserUtil::getInstance()->getUserFromSession();
        $user_id = $userSessionData['user_id'] ?? '';
        $user = new User();
        $userData = $user->findById($user_id);
        
        if (!$userData) {
            $missing_user = LanguagesHelper::getInstance()->getLangLabel('missing_user');
            return self::getFailedResponse(esc_html($missing_user), 400);
        }

        return self::getSuccessResponse();
    }
}