import {HttpException, Injectable} from "@nestjs/common";
import {PgPostService} from "../../shared/pg.post.service";
import {FacebookApi} from "./facebook.api";
import {TwitterClient} from "./twitter.client";
import {normalizeTagsSingleCashtag} from "../../shared/helper";
import {XBrowserService} from "./x-browser.service";
import {XStrategy} from "./x-router.service";
import {buildXCookies} from "./utils/x-headers.util";
import {isEmpty} from "lodash";
import {XCacheService} from "../x-cache/x-cache.service";

@Injectable()
export class PublishPageService {
    constructor(
        private readonly pgPostService: PgPostService,
        private readonly facebookApiService: FacebookApi,
        private readonly twitterClient: TwitterClient,
        private readonly xBrowserService: XBrowserService,
        private readonly cacheService: XCacheService,
    ) {
    }

    async relyX(content: string, tweetId: string) {
        //return this.twitterClient.postReply(content, tweetId);
        // return this.twitterClient.qoute(content, tweetId);
        const tweetUrl = await this.cacheService.getCacheTweetUrlById(tweetId);
        if(isEmpty(tweetUrl)) {
            throw new HttpException(`Không tìm thấy tweet url từ Id : ${tweetId}`, 500);
        }
        return this.xBrowserService.postReply(
            tweetUrl,
            content
        );
    }

    async quoteX(content: string, tweetId: string) {
        // return this.twitterClient.qoute(content, tweetId);
        const tweetUrl = await this.cacheService.getCacheTweetUrlById(tweetId);
        if(isEmpty(tweetUrl)) {
            throw new HttpException(`Không tìm thấy tweet url từ Id : ${tweetId}`, 500);
        }
        return this.xBrowserService.quoteTweet(
            {
                accountId: 'realflashkaze',
                cookies: buildXCookies()
            },
            tweetUrl,
            content
        );
    }

    async publishToFacebook(pgPostId: number): Promise<any> {
        const post = await this.pgPostService.post({id: 1 * pgPostId})
        if (!post) {
            console.log('publishToFacebook:no post was found:', pgPostId);
            return 'no post';
        }

        if (!post.content) {
            console.log('publishToFacebook:Post with no content:', pgPostId);
            return 'no post';
        }
        // if (post.style) {
        //     console.log('Post with no content:', pgPostId);
        //     return 'no post';
        // }
        if (post.status != 'pending') {
            console.log('publishToFacebook:This post already change status', pgPostId);
            return 'This post already change status: ' + pgPostId;
        }
        if (post.isFbPostState > 0) {
            console.log('publishToFacebook:Already posted', pgPostId);
            return 'Already posted on FB: ' + pgPostId;
        }
        console.log('publishToFacebook=>posting')

        const resultPost = await this.facebookApiService.postToPage(post.content);

        await this.pgPostService.updatePost(pgPostId, {
            isFbPostState: 1
        })
        console.log({resultPost});
        console.log('publishToFacebook=>done');
        return resultPost
    }

    async publishTwitter(pgPostIdNum: number, XPostProvider = XStrategy.API_ONLY): Promise<any> {
        const pgPostId = 1 * pgPostIdNum;
        const post = await this.pgPostService.post({id: 1 * pgPostId})
        if (!post) {
            console.log('no post was found:', pgPostId);
            return 'no post';
        }

        if (!post.content) {
            console.log('Post with no content:', pgPostId);
            return 'no post';
        }
        if (post.status != 'pending') {
            console.log('This post already change status', pgPostId);
            return 'This post already change status: ' + pgPostId;
        }
        if (post.isTwitterPostState > 0) {
            console.log('Already posted', pgPostId);
            return 'Already posted on X: ' + pgPostId;
        }
        console.log('publishTwitter=>posting');
        const _normalizeTagsSingleCashtagContent = normalizeTagsSingleCashtag(post.content);

        if (XPostProvider === XStrategy.BROWSER_ONLY) {
            const resp = await this.xBrowserService.postTweet(
                {
                    accountId: 'realflashkaze',
                    cookies: buildXCookies()
                },
                _normalizeTagsSingleCashtagContent
            )
            if (resp.success) {
                await this.pgPostService.updatePost(pgPostId, {
                    isTwitterPostState: 1
                })
            } else {
                console.log('publishTwitter=>posting_error', resp.error);
                throw new HttpException(resp.error || 'exception', 500);
            }
            return;
        }

        if (XPostProvider === XStrategy.API_ONLY) {
            const {data: createdTweet} = await this.twitterClient
                .postSimpleTwitte(_normalizeTagsSingleCashtagContent)
                .catch(err => {
                    console.error(err);
                    const errStatus = err.data.status;
                    // if (errStatus == '401') {
                    //     this.twitterClient.refreshAccessToken();
                    // }
                    const errText = err.data.title;
                    const errDetail = err.data.detail;
                    console.log(`publishTwitter=>posting_err_ ${errText} - ${errStatus} -${errDetail}`)
                    throw new HttpException(errText, errStatus);
                });
            await this.pgPostService.updatePost(pgPostId, {
                isTwitterPostState: 1
            })

            console.log('Tweet', createdTweet.id);
            return {
                ...createdTweet,
                url: `https://x.com/${process.env.TWITTER_USERNAME}/status/${createdTweet.id}`
            }
        }
    }

    async rejectedPost(pgPostIdNum: number): Promise<any> {
        const pgPostId = 1 * pgPostIdNum;

        await this.pgPostService.updatePost(pgPostId, {
            status: 'rejected',
        })

        return pgPostId;
    }

}
