import * as Hapi from "@hapi/hapi";
import Toys from "@hapipal/toys";
import WhatsappService from "./service";

const withDefaults = Toys.withRouteDefaults({
  options: {
    cors: true,
  },
});

const getService = (request: Hapi.Request): WhatsappService => {
  const { whatsappService } = request.services();

  return whatsappService as WhatsappService;
};

interface MessageRequest {
  phoneNumber: string;
  message: string;
}

export const SendMessageRoute = withDefaults({
  method: "post",
  path: "/api/bots/{id}/send",
  options: {
    description: "Send a message",
    async handler(request: Hapi.Request, _h: Hapi.ResponseToolkit) {
      const { id } = request.params;
      console.log({ payload: request.payload });
      const { phoneNumber, message } = request.payload as MessageRequest;
      const whatsappService = getService(request);
      await whatsappService.send(id, phoneNumber, message as string);
      request.logger.info({ id }, "Sent a message at %s", new Date());

      return _h
        .response({
          result: {
            recipient: phoneNumber,
            timestamp: new Date().toISOString(),
            source: id,
          },
        })
        .code(200);
    },
  },
});

export const ReceiveMessageRoute = withDefaults({
  method: "get",
  path: "/api/bots/{id}/receive",
  options: {
    description: "Receive messages",
    async handler(request: Hapi.Request, _h: Hapi.ResponseToolkit) {
      const { id } = request.params;
      const whatsappService = getService(request);
      const date = new Date();
      const twoDaysAgo = new Date(date.getTime());
      twoDaysAgo.setDate(date.getDate() - 2);
      request.logger.info({ id }, "Received messages at %s", new Date());

      return whatsappService.receive(id, twoDaysAgo);
    },
  },
});

export const RegisterBotRoute = withDefaults({
  method: "post",
  path: "/api/bots/{id}/register",
  options: {
    description: "Register a bot",
    async handler(request: Hapi.Request, _h: Hapi.ResponseToolkit) {
      const { id } = request.params;
      const whatsappService = getService(request);

      await whatsappService.register(id);
      /*
      , (error: string) => {
        if (error) {
          return _h.response(error).code(500);
        }
        request.logger.info({ id }, "Register bot at %s", new Date());

        return _h.response().code(200);
      });
       */

      return _h.response().code(200);
    },
  },
});

export const UnverifyBotRoute = withDefaults({
  method: "post",
  path: "/api/bots/{id}/unverify",
  options: {
    description: "Unverify bot",
    async handler(request: Hapi.Request, _h: Hapi.ResponseToolkit) {
      const { id } = request.params;
      const whatsappService = getService(request);

      return whatsappService.unverify(id);
    },
  },
});

export const GetBotRoute = withDefaults({
  method: "get",
  path: "/api/bots/{id}",
  options: {
    description: "Get bot info",
    async handler(request: Hapi.Request, _h: Hapi.ResponseToolkit) {
      const { id } = request.params;
      const whatsappService = getService(request);

      return whatsappService.getBot(id);
    },
  },
});
