import { Injectable, Logger } from '@nestjs/common';
import { fetch } from 'undici';
import type { GlobalWord } from '../global-words/global-word.interface';

interface GenerateResponse {
  path: string;
  mimeType?: string;
}

@Injectable()
export class ImageEngineService {
  private readonly logger = new Logger(ImageEngineService.name);
  private readonly baseUrl = process.env.IMAGE_SERVICE_URL ?? 'http://localhost:8001';

  async generate(word: GlobalWord, slug: string, prompt: string) {
    const response = await fetch(`${this.baseUrl}/generate`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        prompt,
        slug,
        negative_prompt: 'text, watermark, logo, disfigured, deformed',
        width: 640,
        height: 512,
        steps: 4,
      }),
    });

    if (!response.ok) {
      const errorText = await response.text();
      this.logger.error(
        `Image service error ${response.status}: ${errorText}`,
      );
      throw new Error(
        `Image service responded with ${response.status}: ${errorText}`,
      );
    }

    const data = (await response.json()) as GenerateResponse;
    if (!data?.path) {
      throw new Error('Image service did not return a file path');
    }

    return {
      path: data.path,
      mimeType: data.mimeType ?? 'image/png',
    };
  }
}
