import { useSession } from "@tanstack/react-start/server";
import Passwordless from "supertokens-node/recipe/passwordless";
import { sendVerifyCode, updateVerify } from "@/lib/twilio";

const init = () =>
  Passwordless.init({
    flowType: "USER_INPUT_CODE",
    contactMethod: "PHONE",
    smsDelivery: {
      override: (originalImplementation) => {
        return {
          ...originalImplementation,
          sendSms: async ({ userInputCode, phoneNumber, preAuthSessionId }) => {
            if (!userInputCode) {
              throw new Error("No user input code provided to sendSms");
            }

            const sid = await sendVerifyCode(phoneNumber, userInputCode);

            const session = await useSession({
              password: preAuthSessionId,
            });

            await session.update({
              twilioSid: sid,
            });
          },
        };
      },
    },
    override: {
      functions: (originalImplementation) => {
        return {
          ...originalImplementation,
          consumeCode: async (input) => {
            const session = await useSession({
              password: input.preAuthSessionId,
            });
            const twilioSid = session?.data.twilioSid;

            if (!twilioSid) {
              throw new Error("Twilio SID not found in session");
            }

            let response = await originalImplementation.consumeCode(input);

            if (response.status === "OK") {
              await updateVerify(twilioSid);
              await session.update({
                twilioSid: undefined,
                userId: response?.user.id,
              });
            } else if (response.status === "INCORRECT_USER_INPUT_CODE_ERROR") {
              if (
                response.failedCodeInputAttemptCount !==
                response.maximumCodeInputAttempts
              ) {
                await updateVerify(twilioSid);
              }
            }

            return response;
          },
        };
      },
    },
  });

export default { init };
