import { Injectable, Logger, HttpException, HttpStatus } from '@nestjs/common';
import axios from 'axios';
import * as fs from 'fs';
import FormData from 'form-data';

@Injectable()
export class ExtractorService {
  private readonly logger = new Logger(ExtractorService.name);
  private readonly extractorUrl = process.env.EXTRACTOR_URL || 'http://contgen-ai-extractor:8000';

  constructor() {}

  async extractFromUrl(url: string): Promise<string> {
    this.logger.log(`URL'den içerik çekiliyor: ${url}`);
    try {
      const response = await axios.post(`${this.extractorUrl}/extract/url`, { url }, {
        timeout: 60000 // 60 seconds timeout
      });
      return response.data.content;
    } catch (error: any) {
      this.logger.error(`URL extraction failed: ${error.message}`);
      if (error.response) {
        throw new HttpException(error.response.data, error.response.status);
      }
      throw new HttpException('Extractor servisi bulunamadı veya zaman aşımına uğradı', HttpStatus.SERVICE_UNAVAILABLE);
    }
  }

  async extractFromFile(filePath: string, filename: string, mimeType: string): Promise<string> {
    this.logger.log(`Dosyadan içerik çekiliyor: ${filename}`);
    try {
      const formData = new FormData();
      formData.append('file', fs.createReadStream(filePath), {
        filename: filename,
        contentType: mimeType,
      });

      const response = await axios.post(`${this.extractorUrl}/extract/file`, formData, {
        headers: {
          ...formData.getHeaders(),
        },
        timeout: 120000 // 2 minutes timeout for files
      });

      return response.data.content;
    } catch (error: any) {
      this.logger.error(`File extraction failed: ${error.message}`);
      if (error.response) {
        throw new HttpException(error.response.data, error.response.status);
      }
      throw new HttpException('Extractor servisi bulunamadı veya zaman aşımına uğradı', HttpStatus.SERVICE_UNAVAILABLE);
    }
  }
}
