import type { APIGatewayEvent, Context } from 'aws-lambda'

import { logger } from 'src/lib/logger'

/**
 * The handler function is your code that processes http request events.
 * You can use return and throw to send a response or error, respectively.
 *
 * Important: When deployed, a custom serverless function is an open API endpoint and
 * is your responsibility to secure appropriately.
 *
 * @see {@link https://redwoodjs.com/docs/serverless-functions#security-considerations|Serverless Function Considerations}
 * in the RedwoodJS documentation for more information.
 *
 * @typedef { import('aws-lambda').APIGatewayEvent } APIGatewayEvent
 * @typedef { import('aws-lambda').Context } Context
 * @param { APIGatewayEvent } event - an object which contains information from the invoker.
 * @param { Context } _context - contains information about the invocation,
 * function, and execution environment.
 */
export const handler = async (event: APIGatewayEvent, _context: Context) => {
  logger.info(`${event.httpMethod} ${event.path}: oauth function`)

  switch (event.path) {
    case '/oauthStart/microsoft':
      return await callback()
    default:
      return {
        statusCode: 404,
      }
  }
}

const callback = async () => {
  return {
    statusCode: 302,
    headers: {
      Location: `https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${process.env.MICROSOFT_OAUTH_CLIENT_ID}&grant_type=authorization_code&response_type=code&redirect_uri=${process.env.MICROSOFT_OAUTH_REDIRECT_URI}&scope=${process.env.MICROSOFT_OAUTH_SCOPES.split(' ').join('+')}`,
    },
  }
}
