import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { Error400 } from "../../../../utils/customError";
import { UseCase } from "./UseCase";
import { IPayload } from "../../dtos/IPayload";

export class Handler {

  constructor(fastify: FastifyInstance) {}

  async execute(
    request: FastifyRequest,
    reply: FastifyReply
  ): Promise<FastifyReply> {
    try {
      const params = request.body as any;
      const query = request.query as any;

      const payload: IPayload = {
        cliente: query.cliente ?? undefined,
        payload: params
      };

      const useCase = new UseCase();
      await useCase.execute(payload);

      return reply
        .code(204)
        .header("Content-Type", "application/json; charset=utf-8")
        .send();
    } catch (error: any) {
      let statusCode = 500;
      if (error instanceof Error400) statusCode = 400;

      return reply.code(statusCode).send({ message: error.message });
    }
  }

}