import { error } from '../model/error.js';

export const getPasscode = async ({ console, info, fetch, key, cert, p12, password }) => {
    if (key && !cert) {
        const err = new Error('Certificate is missing. Both key and certificate are required for mTLS.');
        throw err;
    }
    if (!key && cert) {
        const err = new Error('Private key is missing. Both key and certificate are required for mTLS.');
        throw err;
    }
    if (p12 && !password) {
        const err = new Error('Password is missing. Password is required to open certificate bundle (P12) file.');
        throw err;
    }
    if (!p12 && password) {
        const err = new Error(
            'Certificate bundle is missing. ' +
            'Both certificate bundle (P12) and password to open it are required for mTLS.');
        throw err;
    }
    if (!cert && !p12) {
        const err = new Error(
            'mTLS credentials are missing. ' +
            'For mTLS either certificate bundle (P12) with password ' +
            'or private key and certificate are required - non of them passed.');
        throw err;
    }
    if (key && cert) {
        console.debug(`Getting passcode with key '${key}' and certificate '${cert}'`);
    } else {
        console.debug(`Getting passcode with certificate bundle '${p12}' and password`);
    }
    if (!info?.issuer) {
        const err = new Error('Authorization server URL (issuer) is missing in info object.');
        throw err;
    }
    const issuerUrl = new URL(
        (info.issuer.startsWith('http://') || info.issuer.startsWith('https://')) ?
            info.issuer :
            'https://' + info.issuer
    );
    issuerUrl.pathname = '/service/users/passcode';
    const res = await fetch(issuerUrl, { tls: { key, cert, p12, password } });
    if (res.status !== 200) {
        throw error(
            `Authentication failed: ${res.status} ${res.statusText} ${await res.text()}`,
            res.status
        );
    }
    return (await res.json())?.passcode;
};
