import type { NextApiRequest, NextApiResponse } from 'next';

import jackson from '@lib/jackson';
import { setErrorCookie } from '@lib/utils';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const { method } = req;

  try {
    if (method !== 'POST') {
      throw { message: `Method ${method} Not Allowed`, statusCode: 405 };
    }

    const { oauthController } = await jackson();

    const { SAMLResponse, RelayState, idp_hint } = req.body as {
      SAMLResponse: string;
      RelayState: string;
      idp_hint: string;
    };

    // Handle SAML Response generated by IdP
    const { redirect_url, app_select_form, response_form } = await oauthController.samlResponse({
      SAMLResponse,
      RelayState,
      idp_hint,
    });

    if (redirect_url) {
      res.redirect(302, redirect_url);
    }

    if (app_select_form) {
      res.setHeader('Content-Type', 'text/html; charset=utf-8');
      res.send(app_select_form);
    }

    if (response_form) {
      res.setHeader('Content-Type', 'text/html; charset=utf-8');
      res.send(response_form);
    }
  } catch (error: any) {
    const { message, statusCode = 500 } = error;

    setErrorCookie(res, { message, statusCode }, { path: '/error' });

    res.redirect(302, '/error');
  }
}
