import { Controller, Get, Logger } from "@nestjs/common";
import { AppService } from './app.service';
import { Ctx, MessagePattern, Payload, RmqContext } from '@nestjs/microservices';
import axios from 'axios';
import { ParsePhotoMessageModel } from './models/parse-photo-message.model';
import { applySmartCrop } from './utils/smartcrop';
import { GuestService } from "./services/guest.service";
@Controller()
export class AppController {
  private readonly logger = new Logger(AppController.name);

  constructor(private readonly appService: AppService, private guestService: GuestService) {}

  @MessagePattern('parse-photo')
  async ParsePhotoMessage(@Payload() data: ParsePhotoMessageModel, @Ctx() context: RmqContext) {
    this.logger.log(`Downloading photo for user: ${data.user}`);
    const file = (
      await axios.get(data.url.toString(), {
        responseType: 'arraybuffer',
      })
    ).data;

    const result = await applySmartCrop(file, '', 450, 450);
    const buff = Buffer.from(result, 'binary').toString('base64');
    this.logger.log(`Applying photo for ${data.user}`);
    await this.guestService.setPhoto(data.user, buff);
    return 'ok';
  }
}
