import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios from 'axios';

@Injectable()
export class FacebookProvider {
  private readonly logger = new Logger(FacebookProvider.name);
  private readonly apiVersion = 'v22.0';
  private accessToken: string;
  private pageId: string;

  constructor(private configService: ConfigService) {
    this.accessToken = this.configService.get<string>('FACEBOOK_ACCESS_TOKEN');
    this.pageId = this.configService.get<string>('FACEBOOK_PAGE_ID');
  }

  async publishPost(content: string, imageUrl: string): Promise<string> {
    this.logger.log(`Publishing post to Facebook: ${content}`);
    try {
      // First upload the image
      const imageUploadResponse = await axios
        .post(
          `https://graph.facebook.com/${this.apiVersion}/${this.pageId}/photos`,
          {
            url: imageUrl,
            caption: content,
            published: false,
          },
          {
            params: { access_token: this.accessToken },
          },
        )
      .catch(error => {
          this.logger.error(`Image upload failed: ${error}`, error);
          throw new Error(`Failed to upload image: ${error.message}`);
        });

      if (!imageUploadResponse || !imageUploadResponse.data) {
        throw new Error('Image upload failed, no response data received');
      }

      this.logger.log(`Image uploaded successfully: ${imageUploadResponse.data.id}`);
      const photoId = imageUploadResponse.data.id;

      if (!photoId) {
        throw new Error('Image upload failed, no photo ID returned');
      }

      // Then create a post with the uploaded image
      this.logger.log(`Creating post with image ID: ${photoId}`);
      const postResponse = await axios.post(
        `https://graph.facebook.com/${this.apiVersion}/${this.pageId}/feed`,
        {
          message: content,
          attached_media: [{ media_fbid: photoId }],
        },
        {
          params: { access_token: this.accessToken },
        },
      );

      this.logger.log(`Post created successfully: ${postResponse.data.id}`);
      return postResponse.data.id;
    } catch (error) {
      this.logger.error(`Facebook post failed: ${error}`, error);
      throw new Error(`Failed to publish to Facebook: ${error.message}`);
    }
  }
}
