// src/modules/social/facebook-api.service.ts
import {Injectable, HttpException, HttpStatus} from '@nestjs/common';
import axios from 'axios';

@Injectable()
export class FacebookApi {
    private readonly fbBaseUrl = 'https://graph.facebook.com/v19.0';
    private readonly pageAccessToken = process.env.FB_PAGE_ACCESS_TOKEN;
    private readonly pageId = process.env.FB_PAGE_ID;

    async postToPage(content: string, imageUrl?: string) {
        // console.log('postToPage==>', content, imageUrl);
        try {
            let url = `${this.fbBaseUrl}/${this.pageId}/feed`;
            let params: any = {
                message: content + `\n  Disclaimer: For reference only. AI content may have errors. Not liable for inaccuracies or damages. Verify from official sources.`,
                access_token: this.pageAccessToken,
            };

            // Nếu có ảnh, chúng ta dùng endpoint /photos
            if (imageUrl) {
                url = `${this.fbBaseUrl}/${this.pageId}/photos`;
                params.url = imageUrl;
            }

            const response = await axios.post(url, params);
            //response.data= { id: '1010286162176053_122107818902775551' }
            return response.data; // Trả về ID bài viết nếu thành công
        } catch (error) {
            console.log('Lỗi khi đăng bài lên FB');
            console.log(error.message);
            throw new HttpException(
                error.response?.data || 'Lỗi khi đăng bài lên FB',
                HttpStatus.BAD_REQUEST,
            );
        }
    }
}
