<?php

namespace EasyLinkAutomations\Actions\Freshservice;

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

use EasyLinkAutomations\Models\Connection;

final class FreshserviceRequestHelper
{
    public static function request(int $connectionId, string $method, string $path, array $body = [], array $query = []): array
    {
        $connection = Connection::find($connectionId);
        if (!$connection) {
            return ['success' => false, 'message' => 'Invalid Freshservice connection', 'data' => []];
        }

        $credentials = Connection::getCredentials($connection);
        $domain = self::domain($credentials['domain'] ?? '');
        $headers = Connection::getAuthHeaders($connectionId);
        if ($domain === '' || empty($headers)) {
            return ['success' => false, 'message' => 'Missing Freshservice credentials', 'data' => []];
        }

        $url = 'https://' . $domain . '.freshservice.com/api/v2/' . ltrim($path, '/');
        if ($query) {
            $url .= '?' . http_build_query($query);
        }

        $args = [
            'method'  => strtoupper($method),
            'headers' => array_merge($headers, ['Accept' => 'application/json', 'Content-Type' => 'application/json']),
            'timeout' => 30,
        ];
        if ($body) {
            $args['body'] = wp_json_encode($body);
        }

        $response = wp_remote_request($url, $args);
        if (is_wp_error($response)) {
            return ['success' => false, 'message' => 'Request failed: ' . $response->get_error_message(), 'data' => []];
        }

        $code = wp_remote_retrieve_response_code($response);
        $raw = wp_remote_retrieve_body($response);
        $decoded = $raw === '' ? [] : json_decode($raw, true);
        $data = json_last_error() === JSON_ERROR_NONE ? $decoded : $raw;
        if ($code < 200 || $code >= 300) {
            return ['success' => false, 'message' => self::failureMessage($code, $data), 'data' => $data];
        }

        return ['success' => true, 'message' => 'Freshservice request completed successfully', 'data' => $data];
    }

    public static function positiveLimit(mixed $value, int $maximum = 100): int
    {
        return max(1, min($maximum, (int) $value));
    }

    private static function domain(mixed $value): string
    {
        $domain = trim((string) $value);
        $host = parse_url($domain, PHP_URL_HOST);
        if (is_string($host) && $host !== '') {
            $domain = $host;
        }
        $domain = preg_replace('#^https?://#i', '', $domain);
        $domain = preg_replace('/\.freshservice\.com$/i', '', trim((string) $domain, '/'));

        return preg_match('/^[a-z0-9][a-z0-9-]*$/i', (string) $domain) ? (string) $domain : '';
    }

    private static function failureMessage(int $code, mixed $data): string
    {
        $message = is_array($data) ? ($data['description'] ?? $data['message'] ?? '') : $data;
        if (is_array($data) && !empty($data['errors'][0]['message'])) {
            $field = $data['errors'][0]['field'] ?? $data['errors'][0]['name'] ?? '';
            $message = ($field !== '' ? $field . ': ' : '') . $data['errors'][0]['message'];
        }

        return 'Freshservice API error (HTTP ' . $code . ')' . ($message !== '' ? ': ' . (string) $message : '');
    }
}
