import { Body, Controller, Get, Header, Logger, Post, Res } from '@nestjs/common';
import { version } from '../package.json';
import { Response } from 'express';
import { generatePDF } from './shared/utils';
import { GetPdfDto } from './users/dto/get-pdf.dto';
import { ConfigurationService } from './configuration/configuration.service';
@Controller()
export class AppController {
  private start = Date.now();
  private readonly logger = new Logger(AppController.name);

  constructor(private configurationService: ConfigurationService) {}

  @Get('healthcheck')
  healthcheck() {
    const now = Date.now();
    return {
      status: 'API Online',
      uptime: Number((now - this.start) / 1000).toFixed(0),
      version: version,
    };
  }

  @Get('config')
  async config() {
    // temp IS_OPENSHIFT: on appsoc servers, GHOST_HOST_AND_PORT is local network server name
    return {
      ghostAdminUrl:
        ((process.env.IS_OPENSHIFT ? process.env.GHOST_HOST_AND_PORT : process.env.GHOST_URL_APPSOC) ||
          'http://localhost:2368') + '/ghost/',
      matomoTrackerUrl: process.env.MATOMO_URL,
      matomoSiteId: process.env.MATOMO_SITEID,
    };
  }

  @Post('/pdf')
  @Header('Content-Type', 'application/pdf')
  @Header('Cache-Control', 'no-cache, no-store, must-revalidate')
  @Header('Pragma', 'no-cache')
  @Header('Expires', '0')
  async getPdf(@Body() body: GetPdfDto, @Res() res: Response): Promise<void> {
    this.logger.log('getPdf: ' + JSON.stringify(body));

    const buffer = await generatePDF(`${this.configurationService.appUrl}/${body.urlPath}`);

    res.set({
      'Content-Disposition': `attachment; filename=${body.fileName}`,
      'Content-Length': buffer.length,
    });
    res.end(buffer);
  }
}