<?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\Utils\OptionUtils;

class DeletePlaylistGuard extends BaseGuard implements GuardInterface {

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

        $fieldsRules = [
            [
                'field_name' => 'playlistId',
                'required' => true,
                'type' => 'string',
                'min_length' => 3,
                'max_length' => 100
            ],
        ];

        $playlistData = $request->get_param('playlistData');

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

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

        if (!UserUtil::isLoggedIn()) {
            $playlist_login_required = LanguagesHelper::getInstance()->getLangLabel('playlist_login_required');
            return self::getFailedResponse(esc_html($playlist_login_required), 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);
        }

        $existingPlaylists = $user->getUserMetaByKey($user_id, 'playlists', []);

        $playlistId = $playlistData['playlistId'];

        $matches = array_filter($existingPlaylists, function($playlist) use ($playlistId) {
            return isset($playlist['id']) && $playlist['id'] === $playlistId;
        });

        $found = reset($matches);

        if ($found === false) {
            return self::getFailedResponse(esc_html__('Missing playlist', 'oxyleaf-app-working-and-relaxing-app'), 400);
        }

        return self::getSuccessResponse();
    }
}