import { Injectable, Logger } from "@nestjs/common";
import ResponseDto from "../../dto/response.dto";
import { EntityManager } from "typeorm";
import { Request } from "express";

@Injectable()
export default class EventsProvider {

    private logger: Logger = new Logger(EventsProvider.name);

    constructor(private readonly entityManager: EntityManager){}

    /**
     * List events
     * @param request 
     * @param id 
     * @returns 
     */
    async listEvents(request: Request, idSkip?: string): Promise<ResponseDto>{

        const response: ResponseDto = new ResponseDto();

        try{

            let where = "";
            if(idSkip){
                const idSkipNum: number = Number.parseInt(idSkip);
                if(isNaN(idSkipNum)){
                    throw new Error("invalid_id_skip");
                }
                where = `WHERE id < ${idSkipNum}`;
            }

            const result = 
                await this.entityManager.query(
                    `
                        SELECT 
                            id, 
                            method,
                            pathname,
                            body,
                            user,
                            created_at createdAt
                        FROM 
                            events
                        ${where}
                        ORDER BY id DESC
                        LIMIT ${process.env.LIMIT_SQL}
                    `
                );

            response.success = true;
            response.data    = { "events": result };

        }catch(e: any){
            this.logger.error(e.message);
        }

        return response;
    }

}