<?php

namespace Itmar\SNS\Twitter;

use WP_Error;
use Itmar\SNS\Tool\HttpTool;

class ApiHelper
{
    public function get_valid_access_token()
    {
        $access_token  = get_option('itmar_twitter_access_token');
        $expires_at    = get_option('itmar_twitter_expires_at');
        $refresh_token = get_option('itmar_twitter_refresh_token');

        if ($access_token && $expires_at && time() < $expires_at) {
            return $access_token;
        }

        if ($refresh_token) {
            return $this->refresh_token($refresh_token);
        }

        return null;
    }

    private function refresh_token($refresh_token)
    {
        $client_id = 'SVhiRzJiLU0tZlZuNkx0YzBjQjA6MTpjaQ';

        $response = wp_remote_post('https://api.twitter.com/2/oauth2/token', [
            'body' => [
                'grant_type'    => 'refresh_token',
                'refresh_token' => $refresh_token,
                'client_id'     => $client_id,
            ],
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded',
            ],
        ]);

        if (is_wp_error($response)) return null;

        $body = json_decode(wp_remote_retrieve_body($response), true);
        if (!isset($body['access_token'])) return null;

        update_option('itmar_twitter_access_token', $body['access_token']);
        update_option('itmar_twitter_refresh_token', $body['refresh_token'] ?? $refresh_token);
        update_option('itmar_twitter_expires_at', time() + intval($body['expires_in'] ?? 7200));

        return $body['access_token'];
    }

    public function get_user_info()
    {
        $user = get_option('itmar_twitter_user');
        if (!is_array($user) || empty($user['id'])) {
            return null;
        }

        return [
            'name' => $user['name'] ?? '',
            'username' => $user['username'] ?? '',
            'avatar_url' => $user['avatar_url'] ?? '',
        ];
    }

    public function create_post($id, $text, $media_infos = [])
    {
        $access_token = $this->get_valid_access_token();
        if (!$access_token) {
            return new WP_Error('no_token', 'Twitter access token not available');
        }

        // 🔎 メディア構成バリデーション
        if (!empty($media_infos)) {
            $validation = $this->validate_media_attachments($media_infos);
            if (is_wp_error($validation)) {
                return $validation;
            }
        }
        $get_urls = [];
        foreach ($media_infos as $media) {
            $img_url = $media['url'];
            $get = HttpTool::upload_to_s3($img_url, $access_token);
            $get_urls[] = $get['get_url'];
        }

        // AWSに処理を任せる
        $api_base = rtrim(ITMAR_AWS_BASE_URL, '/');
        $body_arr = wp_json_encode(
            [
                'media_urls' => $get_urls,
                'wp_id' => $id,
                'text' => $text,
                'expires' => 900,
            ],
            JSON_UNESCAPED_SLASHES
        );

        $res = wp_remote_post("$api_base/x/start_upload", [
            'headers' => array_filter([
                'Content-Type' => 'application/json',
                'X-X-Token'  => $access_token,
                'X-Site-Url'      => home_url()
            ]),
            'body'    => $body_arr,
            'timeout' => 30,
        ]);

        return $res;
    }

    public function delete_post($tweet_id)
    {
        $access_token = $this->get_valid_access_token();

        if (!$access_token) {
            return new WP_Error('no_token', 'Twitter access token not available');
        }

        $url = "https://api.twitter.com/2/tweets/{$tweet_id}";

        $response = wp_remote_request($url, [
            'method'  => 'DELETE',
            'headers' => [
                'Authorization' => 'Bearer ' . $access_token,
                'Content-Type'  => 'application/json',
            ],
            'timeout' => 15,
        ]);

        if (is_wp_error($response)) {
            return $response;
        }

        $code = wp_remote_retrieve_response_code($response);
        $body = json_decode(wp_remote_retrieve_body($response), true);

        if ($code !== 200) {
            $msg = $body['title'] ?? 'Unknown error';
            return new WP_Error('delete_failed', "削除に失敗しました: {$msg}");
        }

        return true;
    }

    private function validate_media_attachments($media_infos)
    {
        $image_count = 0;
        $video_count = 0;

        foreach ($media_infos as $media) {
            $type = $media['type'] ?? 'img';
            $url = $media['url'] ?? '';

            if ($type === 'img') {
                $image_count++;
                $max_size = 5 * 1024 * 1024; // 5MB
            } elseif ($type === 'video') {
                $video_count++;
                $max_size = 512 * 1024 * 1024; // 512MB
            } else {
                return new WP_Error('invalid_type', '無効なメディアタイプが指定されました。');
            }

            $head = wp_remote_head($url, ['sslverify' => true]);
            if (is_wp_error($head)) {
                return $head;
            }

            $length = wp_remote_retrieve_header($head, 'content-length');
            if ($length && $length > $max_size) {
                return new WP_Error('media_too_large', 'メディアファイルが上限を超えています。');
            }
        }

        if ($video_count > 1) {
            return new WP_Error('too_many_videos', '動画は1つしか投稿できません。');
        }

        if ($image_count > 4) {
            return new WP_Error('too_many_images', '画像は最大4枚までしか投稿できません。');
        }

        if ($video_count > 0 && $image_count > 0) {
            return new WP_Error('media_mixed', '画像と動画を同時に投稿することはできません。');
        }

        return true;
    }
}
