import {
  BadRequestException,
  Injectable,
  Logger,
  ServiceUnavailableException,
} from '@nestjs/common';
import { downloadAndOptimizeImage } from '../common/utils/download-image';

const IMAGE_DEST_DIR = process.env.IMAGE_DEST_DIR || '/app/recipe-images';
const IMPORTER_SERVICE_URL =
  process.env.IMPORTER_SERVICE_URL || 'http://importer-api:3001';

export interface QuickImportResult {
  markdown: string;
  source: 'ica' | 'pdf' | 'image' | 'other';
  imageUrl?: string;
  imageWarning?: string;
}

@Injectable()
export class QuickImportService {
  private readonly logger = new Logger(QuickImportService.name);

  async importFromInput(input: string): Promise<QuickImportResult> {
    const trimmed = input.trim();
    this.logger.log(`Delegerar URL-import till microservice: ${trimmed}`);

    if (!trimmed) {
      throw new BadRequestException('Du mÃ¥ste ange en URL eller ladda upp en fil');
    }

    let response: Response;
    try {
      response = await fetch(`${IMPORTER_SERVICE_URL}/api/quick-import`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ input: trimmed }),
      });
    } catch (err) {
      this.logger.error(`Kunde inte nÃ¥ importer-api: ${err}`);
      throw new ServiceUnavailableException(
        'Import-tjÃ¤nsten Ã¤r inte tillgÃ¤nglig. FÃ¶rsÃ¶k igen senare.',
      );
    }

    const result = await this.handleImporterResponse(response);
    return this.downloadImageIfNeeded(result);
  }

  async importFromUpload(file: Express.Multer.File): Promise<QuickImportResult> {
    this.logger.log(`Delegerar filuploading till microservice: ${file.originalname} (${file.mimetype})`);

    const form = new FormData();
    form.append(
      'file',
      new Blob([new Uint8Array(file.buffer)], { type: file.mimetype }),
      file.originalname,
    );

    let response: Response;
    try {
      response = await fetch(`${IMPORTER_SERVICE_URL}/api/quick-import`, {
        method: 'POST',
        body: form,
      });
    } catch (err) {
      this.logger.error(`Kunde inte nÃ¥ importer-api: ${err}`);
      throw new ServiceUnavailableException(
        'Import-tjÃ¤nsten Ã¤r inte tillgÃ¤nglig. FÃ¶rsÃ¶k igen senare.',
      );
    }

    const result = await this.handleImporterResponse(response);
    return this.downloadImageIfNeeded(result);
  }

  private async handleImporterResponse(response: Response): Promise<QuickImportResult> {
    if (!response.ok) {
      let message = `Import-tjÃ¤nsten svarade ${response.status}`;
      try {
        const body = (await response.json()) as { message?: string };
        if (body.message) message = body.message;
      } catch {
        // ignorera parse-fel
      }
      this.logger.error(`Importer-api fel: ${message}`);
      if (response.status >= 400 && response.status < 500) {
        throw new BadRequestException(message);
      }
      throw new ServiceUnavailableException(message);
    }
    return response.json() as Promise<QuickImportResult>;
  }

  private async downloadImageIfNeeded(result: QuickImportResult): Promise<QuickImportResult> {
    if (!result.imageUrl) return result;

    const imageUrl = result.imageUrl;
    if (!imageUrl.startsWith('http://') && !imageUrl.startsWith('https://')) {
      return result;
    }

    this.logger.log(`Laddar ner receptbild: ${imageUrl}`);
    try {
      const localPath = await downloadAndOptimizeImage(imageUrl, IMAGE_DEST_DIR);
      this.logger.log(`Bild sparad lokalt: ${localPath}`);
      return { ...result, imageUrl: localPath };
    } catch (imgErr) {
      this.logger.warn(`Kunde inte ladda ner bild: ${imgErr} (kÃ¤lla: ${imageUrl})`);
      return {
        ...result,
        imageWarning: result.imageWarning ?? 'Receptbild kunde inte laddas ner lokalt; extern URL anvÃ¤nds.',
      };
    }
  }
}
