<?php
if (!defined('ABSPATH')) {
    exit;
}

class VMO_Promotion_Tumblr_Connector extends VMO_Promotion_OAuth2_Connector {
    protected function build_authorization_url(array $settings, array $scopes, $state) {
        return add_query_arg(array(
            'response_type' => 'code',
            'client_id' => $this->get_client_identifier($settings),
            'redirect_uri' => $this->get_callback_url(),
            'scope' => implode(' ', $scopes),
            'state' => $state,
        ), 'https://www.tumblr.com/oauth2/authorize');
    }

    protected function get_token_endpoint() {
        return 'https://api.tumblr.com/v2/oauth2/token';
    }

    protected function discover_remote_accounts($user_id, array $token_context, array $request_context = array()) {
        $access_token = (string) ($token_context['access_token'] ?? '');
        if ($access_token === '') {
            return array();
        }

        $response = $this->tumblr_request('GET', 'https://api.tumblr.com/v2/user/info', $access_token);
        if (is_wp_error($response)) {
            return $response;
        }

        $user = (array) ($response['response']['user'] ?? array());
        $blogs = array_values((array) ($user['blogs'] ?? array()));
        $accounts = array();

        foreach ($blogs as $blog) {
            $blog_name = sanitize_text_field($blog['name'] ?? '');
            if ($blog_name === '') {
                continue;
            }

            $accounts[] = array(
                'platform_key' => 'tumblr',
                'platform_label' => 'Tumblr',
                'external_account_id' => $blog_name,
                'display_name' => sanitize_text_field($blog['title'] ?? $blog_name),
                'auth_status' => 'connected',
                'connection_metadata' => array(
                    'connection_role' => 'tumblr_blog',
                    'blog_name' => $blog_name,
                    'blog_url' => esc_url_raw($blog['url'] ?? ''),
                    'is_primary' => !empty($blog['primary']),
                    'followers' => (int) ($blog['followers'] ?? 0),
                    'tweet_auto' => sanitize_text_field($blog['tweet'] ?? ''),
                ),
            );
        }

        if (empty($accounts) && !empty($user['name'])) {
            $username = sanitize_text_field($user['name']);
            $accounts[] = array(
                'platform_key' => 'tumblr',
                'platform_label' => 'Tumblr',
                'external_account_id' => $username,
                'display_name' => $username,
                'auth_status' => 'connected',
                'connection_metadata' => array(
                    'connection_role' => 'tumblr_user',
                    'blog_name' => $username,
                ),
            );
        }

        return $accounts;
    }

    public function publish_text_post(array $input) {
        $account = $this->get_platform_account_record($input);
        if (empty($account['access_token'])) {
            return new WP_Error('missing_connected_account', 'A connected Tumblr blog is required before publishing.');
        }

        $blog_name = sanitize_text_field($account['connection_metadata']['blog_name'] ?? $account['external_account_id'] ?? '');
        if ($blog_name === '') {
            return new WP_Error('missing_blog_identifier', 'This Tumblr connection is missing the target blog identifier.');
        }

        $content_item = (array) ($input['content_item'] ?? array());
        $title = sanitize_text_field($content_item['title'] ?? '');
        $body = $this->get_post_caption($content_item);
        if ($body === '' && $title === '') {
            return new WP_Error('missing_post_text', 'Tumblr publishing requires post text or a title.');
        }

        if ($body === '') {
            $body = $title;
        } elseif ($title !== '') {
            $body = $title . "\n\n" . $body;
        }

        $response = $this->tumblr_request(
            'POST',
            'https://api.tumblr.com/v2/blog/' . rawurlencode($blog_name) . '/post',
            $account['access_token'],
            array(
                'type' => 'text',
                'body' => $body,
                'state' => 'published',
            ),
            true
        );
        if (is_wp_error($response)) {
            return $response;
        }

        return array(
            'provider_post_id' => sanitize_text_field($response['response']['id_string'] ?? $response['response']['id'] ?? ''),
            'message' => 'Published to Tumblr.',
            'response' => $response,
        );
    }

    public function publish_media_post(array $input) {
        return new WP_Error('provider_not_ready', 'Tumblr media publishing is not activated yet in this build. Text publishing is available, but media post assembly still needs provider-specific handling.');
    }

    public function list_replies(array $input) {
        return new WP_Error('provider_not_ready', 'Tumblr reply ingestion is not activated yet in this build.');
    }

    public function reply_to_comment(array $input) {
        return new WP_Error('provider_not_ready', 'Tumblr reply publishing is not activated yet in this build.');
    }

    public function fetch_metrics(array $input) {
        return new WP_Error('provider_not_ready', 'Tumblr metrics normalization is not finalized yet in this build.');
    }

    protected function tumblr_request($method, $url, $access_token, array $body = array(), $form_encoded = false) {
        $args = array(
            'method' => strtoupper($method),
            'timeout' => 30,
            'headers' => array(
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $access_token,
                'User-Agent' => 'VMO Promotion Connector',
            ),
        );

        if ($args['method'] !== 'GET' && !empty($body)) {
            if ($form_encoded) {
                $args['headers']['Content-Type'] = 'application/x-www-form-urlencoded';
                $args['body'] = $body;
            } else {
                $args['headers']['Content-Type'] = 'application/json';
                $args['body'] = wp_json_encode($body);
            }
        }

        $response = wp_remote_request($url, $args);
        if (is_wp_error($response)) {
            return $response;
        }

        $status = (int) wp_remote_retrieve_response_code($response);
        $data = json_decode((string) wp_remote_retrieve_body($response), true);
        if (!is_array($data)) {
            $data = array();
        }

        if ($status >= 400 || (!empty($data['meta']['status']) && (int) $data['meta']['status'] >= 400)) {
            return new WP_Error(
                'provider_api_error',
                sanitize_text_field($data['meta']['msg'] ?? $data['errors'][0]['detail'] ?? 'Tumblr API request failed.'),
                array(
                    'platform_key' => 'tumblr',
                    'status' => $status,
                    'response' => $data,
                )
            );
        }

        return $data;
    }
}
