// x-cookie.service.ts
import {Injectable, Logger, BadRequestException} from '@nestjs/common';
import axios, {AxiosInstance} from 'axios';
import {HttpsProxyAgent} from 'https-proxy-agent';
import {CreateTweetDto} from './dto/create-tweet.dto';
import {XCookieAccount, TweetResult} from './interfaces/x-cookie.interface';
import {buildXHeaders, X_COOKIE_NAME} from './utils/x-headers.util';
import {ConfigService} from "@nestjs/config";
import {parse} from "cookie";

interface GraphQLVariables {
    [key: string]: any;
}


@Injectable()
export class XCookieService {
    private readonly logger = new Logger(XCookieService.name);
    private readonly client: AxiosInstance;
    private userId: string;
    private queryID: string;
    private screenName: string | null = null;
    private TWEET_URL = '';
    // Endpoint GraphQL tạo tweet (queryId có thể đổi theo thời gian)
    private readonly CREATE_TWEET_URL =
        'https://x.com/i/api/graphql/bDE2rBtZb3uyrczSZ_pI9g/CreateTweet';

    constructor(private readonly config: ConfigService) {
        // ── Lấy cookie từ env ──
        const authToken = X_COOKIE_NAME.auth_token;
        const ct0 = X_COOKIE_NAME.cto;
        const kdt = X_COOKIE_NAME.kdt;
        // const authToken = this.config.get<string>('TWITTER_AUTH_TOKEN');
        // const ct0 = this.config.get<string>('TWITTER_CT0')!;
        this.queryID = this.config.get<string>('TWITTER_QUERY_ID') || '';

        const createQid = this.config.get<string>('TWITTER_CREATE_TWEET_QUERY_ID') || 'Qkq4oPdZYuNB_Qw3TDuFqQ';
        this.TWEET_URL = `https://x.com/i/api/graphql/${createQid}/CreateTweet`;


        // Bearer token này gần như cố định cho Web App, có thể để default
        const bearer = 'AAAAAAAAAAAAAAAAAAAAAF7OAAAAAAAPS6nVJjCEf6gW6rLVnQujDGAh8%3DkQS5VtDfPBTSO89WMK4HvSpSUYshWVio9dNNWQEvwfkGmL7nPF';

        // Ghép chuỗi cookie để axios gửi kèm request
        const cookies = [
            `auth_token=${authToken}`,
            `ct0=${ct0}`,
            `kdt=${kdt}`,
        ].join('; ');

        const cookie = `__cuid=4035196cccd84e129f04429c872518a7; twid=u%3D2043937828644536320; guest_id_ads=v1%3A177685259136534867; guest_id_marketing=v1%3A177685259136534867; __cf_bm=hrKUIMlfUs3DfWLr3eOohfxqagtyPQVnHiLOu.Ogtu0-1777886768.8740897-1.0.1.1-ubUA2SEhNiWFs.uruUZ98qVRHCn_EoEmeKqsXTa1RjeOvd9CTXKkF3Su3mTf4fbr4.GdQPb5QClU0JE2raMBRBL_I6NmM.sqm0hKe5tOuF3AxxVXQb4J5.Dcw9uKpio9; external_referer=padhuUp37zjgzgv1mFWxJ12Ozwit7owX|0|8e8t2xd8A2w%3D; personalization_id="v1_plsX3tTzuhmy/NMuFYA8zg=="; ads_prefs="HBISAAA="; auth_token=f5574950a0d98cf49ca2e574cc6a4139cc8a2d81; ct0=75db96b40f4814925670722e3335840467b87c7eb403aab14fbe719297bf465347810f92dc2116c3d30f15153a332976c50d856983dfe19046d4f10413b3d1cd8bac6f7a99e5b03c6949bafdad0f01c0; dnt=1; guest_id=v1%3A177685259136534867; lang=en; _twpid=tw.1776151761301.87290159275149142; kdt=2JWxVxk3NZUEjkorxsQE6ilftoYnFQDI8u5IgsBz; __eoi=ID=1d23cba9bef5792f:T=1776090662:RT=1776090662:S=AA-AfjYo3lmC9kyBbnzpvdA3zf9a; __gads=ID=72ac119a9545f1cf:T=1776090662:RT=1776090662:S=ALNI_MYl23FAc-out8xXJykggkJnCBrxFQ; __gpi=UID=00001252726e7c96:T=1776090662:RT=1776090662:S=ALNI_MZUcHGy1ZnZJP5-uU2_I8WMY75QUA; cf_clearance=9R0VPss1VjPR85IFC8i9ydboDzfnQFh0pdZMmkgzpZk-1774104987-1.2.1.1-.Io13bhStMnBLS17Vl2TQfMafDfwpglq50K7Jc22v9k0eihCURaZu8dTy1imZyfVCUt227dQvQWVHJY1mSL8wUqmWCX9PIXSPrgcn_4A1qroXXYqpwQ1U0.UhtzIPplj3sCYqsJKnJ_BR981amqOpcpNV9IFIBERk70vIFPU0o5TIOFpkhCddj3Xhb3yxmZ82w3o95m2XVKw0wm_yXEEXypOJTl7Ubn5zYw3520gX_Q; d_prefs=MjoxLGNvbnNlbnRfdmVyc2lvbjoyLHRleHRfdmVyc2lvbjoxMDAw; ph_phc_TXdpocbGVeZVm5VJmAsHTMrCofBQu3e0kN8HGMNGTVW_posthog=%7B%22distinct_id%22%3A%2201991503-adac-7662-9300-2c5ed339def2%22%2C%22%24sesid%22%3A%5B1757078963247%2C%2201991a11-3e32-731b-b131-dd286bdf9c08%22%2C1757078961713%5D%7D`;

        // ── Tạo axios instance với header giả lập browser ──
        // this.client = axios.create({
        //     timeout: 30000,
        //     headers: {
        //         'authorization': `Bearer ${bearer}`,
        //         'content-type': 'application/json',
        //         'cookie': cookies,              // <-- Cookie đăng nhập
        //         'x-csrf-token': ct0,            // <-- BẮT BUỘC, không có là lỗi 403
        //         'x-twitter-auth-type': 'OAuth2Session',
        //         'x-twitter-client-language': 'en',
        //         'x-twitter-active-user': 'yes',
        //         'referer': 'https://x.com/home',
        //         'user-agent':
        //             'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
        //     },
        // });
        // const cookies = parse(cookie);
        // console.log(cookies);
        // this.userId = cookies.twid?.split('u=')[1] || '';
        // if (!this.userId) throw new Error('Missing twid cookie (user ID)');
        console.log(`userId=${this.userId}`);
        this.client = axios.create({
            baseURL: 'https://x.com/i/api',
            headers: {
                'authorization': 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
                'x-csrf-token': ct0,
                'x-twitter-auth-type': 'OAuth2Session',
                'x-twitter-active-user': 'yes',
                'x-twitter-client-language': 'en',
                'content-type': 'application/json',
                'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
                'cookie': cookies,  // 'auth_token=xxx; ct0=yyy; ...' full string từ devtools
                'referer': 'https://x.com/compose/tweet',
                'origin': 'https://x.com',
            },
            timeout: 10000,
        });

        // Interceptor: log lỗi chi tiết nếu bị 403/404/400
        this.client.interceptors.response.use(
            (res) => res,
            (err) => {
                const status = err.response?.status;
                const errors = err.response?.data?.errors;
                this.logger.log(`Call Url: ${err.config.url}`)
                this.logger.error(`Twitter HTTP ${status}:`, errors || err.message);
                return Promise.reject(err);
            },
        );
    }

    private buildClient(account: XCookieAccount): AxiosInstance {
        const config: any = {
            headers: buildXHeaders(account.authToken, account.ct0),
            timeout: 20000,
        };

        if (account.proxy) {
            const agent = new HttpsProxyAgent(account.proxy);
            config.httpsAgent = agent;
            config.proxy = false;
        }

        const client = axios.create(config);
        // Interceptor: log lỗi chi tiết nếu bị 403/404/400
        client.interceptors.response.use(
            (res) => res,
            (err) => {
                const status = err.response?.status;
                const errors = err.response?.data?.errors;
                this.logger.log(`Call Url: ${err.config.url}`)
                this.logger.error(`Twitter HTTP ${status}:`, errors || err.message);
                return Promise.reject(err);
            },
        );
        return client;
    }

    /**
     * ĐĂNG TWEET đơn
     */
    async createTweet(text: string): Promise<{ id: string; url: string }> {
        const payload = {
            variables: {
                tweet_text: text,
                dark_request: false,
                media: {media_entities: [], possibly_sensitive: false},
                semantic_annotation_id: [],
            },
            features: {
                tweets_nudges_moments: true,
                tweet_with_visibility_results_prefetch_gql_enabled: true,
                longform_notetweets_consumption_enabled: true,
                responsive_web_edit_tweet_api_enabled: true,
                graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,
                view_counts_everywhere_api_enabled: true,
                interactive_text_enabled: true,
                responsive_web_text_conversations_enabled: false,
                longform_notetweets_richtext_consumption_enabled: false,
                responsive_web_enhance_cards_enabled: false,
            },
        };

        const res = await this.client.post(this.TWEET_URL, payload);

        const result = res.data?.data?.create_tweet?.tweet_results?.result;
        if (!result) {
            throw new Error(`CreateTweet failed: ${JSON.stringify(res.data)}`);
        }

        const tid = result.rest_id;
        const screenName = result.core?.user_results?.result?.legacy?.screen_name || 'i';
        return {id: tid, url: `https://x.com/${screenName}/status/${tid}`};
    }

    // async createTweet(
    //     account: XCookieAccount,
    //     dto: CreateTweetDto,
    // ): Promise<TweetResult> {
    //     const client = this.buildClient(account);
    //
    //     const variables: any = {
    //         tweet_text: dto.text,
    //         dark_request: false,
    //         media: {
    //             media_entities: (dto.mediaIds ?? []).map((id) => ({
    //                 media_id: id,
    //                 tagged_users: [],
    //             })),
    //             possibly_sensitive: false,
    //         },
    //         semantic_annotation_ids: [],
    //         disallowed_reply_hashtags: [],
    //     };
    //
    //     if (dto.replyToTweetId) {
    //         variables.reply = {
    //             in_reply_to_tweet_id: dto.replyToTweetId,
    //             exclude_reply_user_ids: [],
    //         };
    //     }
    //
    //     const features = {
    //         communities_web_enable_tweet_community_results_fetch: true,
    //         c9s_tweet_anatomy_moderator_badge_enabled: true,
    //         responsive_web_edit_tweet_api_enabled: true,
    //         graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,
    //         view_counts_everywhere_api_enabled: true,
    //         longform_notetweets_consumption_enabled: true,
    //         responsive_web_twitter_article_tweet_consumption_enabled: true,
    //         tweet_awards_web_tipping_enabled: false,
    //         creator_subscriptions_quote_tweet_preview_enabled: false,
    //         longform_notetweets_rich_text_read_enabled: true,
    //         longform_notetweets_inline_media_enabled: true,
    //         rweb_video_timestamps_enabled: true,
    //         responsive_web_graphql_exclude_directive_enabled: true,
    //         verified_phone_label_enabled: false,
    //         freedom_of_speech_not_reach_fetch_enabled: true,
    //         standardized_nudges_misinfo: true,
    //         tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,
    //         responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,
    //         responsive_web_graphql_timeline_navigation_enabled: true,
    //         responsive_web_enhance_cards_enabled: false,
    //     };
    //
    //     try {
    //         const {data} = await client.post(this.CREATE_TWEET_URL, {
    //             variables,
    //             features,
    //             queryId: 'bDE2rBtZb3uyrczSZ_pI9g',
    //         });
    //
    //         const tweetId =
    //             data?.data?.create_tweet?.tweet_results?.result?.rest_id;
    //
    //         if (!tweetId) {
    //             this.logger.warn('Tweet created but no id found', data);
    //             return {success: false, error: 'No tweet id returned'};
    //         }
    //
    //         return {success: true, tweetId};
    //     } catch (err: any) {
    //         const msg =
    //             err.response?.data?.errors?.[0]?.message ||
    //             err.message ||
    //             'Unknown error';
    //         this.logger.error(`Create tweet failed: ${msg}`);
    //
    //         if (err.response?.status === 401 || err.response?.status === 403) {
    //             throw new BadRequestException(
    //                 'Cookie expired or invalid. Need re-login.',
    //             );
    //         }
    //
    //         return {success: false, error: msg};
    //     }
    // }


    /**
     * VERIFY COOKIE (FIX lỗi 34): Dùng GraphQL UserByRestId (hash ổn định hơn v1.1)
     * @param userHandle Optional: Nếu biết @username
     */
    async verifyCookie(userHandle?: string): Promise<{ screen_name: string; name: string }> {
        try {
            let variables: GraphQLVariables;
            let queryId: string;

            // if (userHandle) {
            // UserByScreenName (hash hiện tại 2026: extract nếu lỗi)
            queryId = 'IGgvgiOx4QZndDHuD3x9TQ';  // PLACEHOLDER → Extract (xem dưới)
            variables = {
                "screen_name": userHandle,
                "withSafetyModeUserFields": true,
                "withSuperFollowsUserFields": true
            };
            // }
            // else {
            //     // UserByRestId (dùng userId từ twid)
            //     queryId = 'IGgvgiOx4QZndDHuD3x9TQ';  // Placeholder → Extract
            //     variables = { "userId": this.userId, "withSafetyModeUserFields": true, "withSuperFollowsUserFields": true };
            // }

            const account = {
                authToken: X_COOKIE_NAME.auth_token,
                ct0: X_COOKIE_NAME.cto,
            }
            const client = this.buildClient(account);
            const res = await client.get(`/graphql/${this.queryID}/UserByScreenName?variables=%7B%22screen_name%22%3A%22realflashkaze%22%2C%22withSafetyModeUserFields%22%3Atrue%7D&features=%7B%7D`, {  // Hoặc UserByScreenName
                // features: {
                //     "rweb_tipjar_consumption_enabled":true,
                //     "responsive_web_graphql_exclude_directive_enabled":true,
                //     "verified_phone_label_enabled":false,
                //     "creator_subscriptions_tweet_preview_api_enabled":true,
                //     "responsive_web_graphql_timeline_navigation_enabled":true,
                //     "responsive_web_graphql_skip_user_profile_image_extensions_enabled":false,
                //     "communities_web_preview_enabled":true
                // },
                // Add more features nếu cần (copy từ devtools)
            });
            return res.data.data.user;
            const user = res.data.data.user;  // Hoặc res.data.data.result
            this.screenName = user.rest_id ? user.legacy.screen_name : user.screen_name;
            this.logger.log(`Verified: @${this.screenName}`);
            return {screen_name: this.screenName!, name: user.legacy.name};
        } catch (error: any) {
            this.logger.error(`Verify failed: ${error.response?.data?.errors?.[0]?.message || error.message}`);
            throw error;
        }
    }


    /**
     * Gọi Twitter API v1.1 để kiểm tra cookie còn sống.
     * Nếu cookie chết sẽ throw lỗi 401/403.
     */
    async getCurrentUser(): Promise<{ id: string; screen_name: string; name: string }> {
        const url = 'https://api.twitter.com/1.1/account/verify_credentials.json?skip_status=true';

        const res = await this.client.get(url);
        const data = res.data;

        if (!data?.screen_name) {
            throw new Error('verify_credentials không trả về screen_name');
        }

        return {
            id: data.id_str,
            screen_name: data.screen_name,
            name: data.name,
        };
    }

    /**
     * Kiểm tra nhanh: true = sống, false = chết (không throw)
     */
    async isCookieAlive(): Promise<boolean> {
        try {
            await this.getCurrentUser();
            return true;
        } catch {
            return false;
        }
    }
}
