import {Injectable, Logger} from "@nestjs/common";
import {TwitterClient} from "../social-api/twitter.client";
import axios from "axios";

@Injectable()
export class XImageUploadService {
    private readonly logger = new Logger(XImageUploadService.name);

    constructor(private readonly client: TwitterClient) {
    }

    async uploadImageFromUrl(imageUrl: string) {
        // 1. download image
        const response = await axios.get(imageUrl, {
            responseType: 'arraybuffer',
        });

        // // 3. download buffer
        // const img = await axios.get(fileUrl, {
        //     responseType: 'arraybuffer',
        // });
        //
        // const buffer = Buffer.from(img.data);
        const buffer = Buffer.from(response.data);

        await this.client.uploadImageV1(buffer, {
            media_type: 'image/png',
            media_category: 'tweet_image',

        });

       // return res.data.media_id_string;
    }

    async getTelegramFileUrl(fileId: string): Promise<string> {
        const token = process.env.TELEGRAM_BOT_TOKEN;

        const res = await axios.get(
            `https://api.telegram.org/bot${token}/getFile?file_id=${fileId}`
        );

        const filePath = res.data.result.file_path;

        return `https://api.telegram.org/file/bot${token}/${filePath}`;
    }

    async uploadFromTelegram(fileId: string) {
        const url = await this.getTelegramFileUrl(fileId);
        const mediaId = await this.uploadImageFromUrl(url);

        return mediaId;
    }
}
