import { Body, JsonController, Post, QueryParam, Res } from 'routing-controllers';
import { OpenAPI } from 'routing-controllers-openapi';
import { Runner } from '../models/Runner';
import { PdfCreator } from '../PdfCreator';

/**
 * The pdf controller handels all endpoints concerning pdf generation.
 * It therefore is the hearth of the document-generation server's endpoints.
 * All endpoints have to accept a locale query-param to support i18n. 
 */
@JsonController()
export class PdfController {
    private pdf: PdfCreator = new PdfCreator();
    private initialized: boolean = false;

    @Post('/contracts')
    @OpenAPI({ description: "Generate Sponsoring contract pdfs from runner objects.<br>You can choose your prefered locale by passing the 'locale' query-param.<br> If you provide more than 100 runenrs this could take a moment or two (we tested up to 1000 runners in about 70sec so far)." })
    async generateContracts(@Body({ validate: true, options: { limit: "500mb" } }) runners: Runner | Runner[], @Res() res: any, @QueryParam("locale") locale: string) {
        if (!this.initialized) {
            await this.pdf.init();
            this.initialized = true;
        }
        if (!Array.isArray(runners)) {
            runners = [runners];
        }
        const contracts = await this.pdf.generateSponsoringContract(runners, locale);
        res.setHeader('content-type', 'application/pdf');
        return contracts;
    }
}
