import { TwilioResponse } from "@twilio-labs/serverless-runtime-types/types";
import { TwilioContext } from "../types/TwilioContext";
import { sealData, unsealData } from "iron-session";
import { DoormanLambdaContext } from "./DoormanHandlerContext";

export type BaseEvent = { request: { cookies: { session?: string; }; headers: {}; session?: SessionType }; }

export type SessionType = any;
export const IRON_SESSION_COOKIE_NAME = "session";

export async function getSessionFromRequest(event: BaseEvent, context: DoormanLambdaContext): Promise<SessionType | undefined> {
  if (!event.request.cookies[IRON_SESSION_COOKIE_NAME]) {
    return undefined
  }

  let session: SessionType | undefined;
  try {
    session = await unsealData<any>(event.request.cookies[IRON_SESSION_COOKIE_NAME], {
      password: context.COOKIE_PASSWORD,
    });
  } catch (e: any) {
    console.error("error unsealing cookie");
  }

  return session;
}

export async function setSessionOnResponse(res: TwilioResponse, context: TwilioContext, session: any): Promise<TwilioResponse> {
  if (!session) {
    return res;
  }

  try {
    const cookie = await sealData(session, {
      password: context.COOKIE_PASSWORD,
    });
    console.log(cookie);
    res.setCookie(IRON_SESSION_COOKIE_NAME, cookie);
  } catch (e: any) {
    console.log("failed to seal cookie");
    console.log(e.message);
  }

  return res;
}

export async function destroySession(res: TwilioResponse): Promise<TwilioResponse> {
  res.removeCookie(IRON_SESSION_COOKIE_NAME);
  return res;
}
