import { Request, Response, NextFunction } from 'express';
import { BadRequestError } from '../httpErrors.js';

declare global {
  // eslint-disable-next-line @typescript-eslint/no-namespace
  namespace Express {
    interface Locals {
      credentials: Credentials;
    }
  }
}

/**
 * The credentials object passed to every handler function.
 *
 * It contains the parsed credentials payload associated with the request through the X-Unito-Credentials header.
 */
export type Credentials = {
  /**
   * The access token for the provider.
   */
  accessToken?: string;
  /**
   * The id of the unito credential record.
   *
   * This is not available on the initial call to /me before the creation of the credential.
   */
  unitoCredentialId?: string;
  /**
   * The id of the unito user record.
   */
  unitoUserId?: string;
  [keys: string]: unknown;
};

const CREDENTIALS_HEADER = 'X-Unito-Credentials';

function extractCredentials(req: Request, res: Response, next: NextFunction) {
  const credentialsHeader = req.header(CREDENTIALS_HEADER);

  if (credentialsHeader) {
    let credentials: Credentials;

    try {
      credentials = JSON.parse(Buffer.from(credentialsHeader, 'base64').toString('utf8'));
    } catch {
      throw new BadRequestError(`Malformed HTTP header ${CREDENTIALS_HEADER}`);
    }

    res.locals.credentials = credentials;
  }

  next();
}

export default extractCredentials;
