import {Logger, logSetup} from "./logger";
import {fetch_timeout} from "./util";
import {API_ROOT} from "./config";
import type {UserInfo} from "./auth";

const logger = new Logger("orgs.ts");
logSetup();

export interface Organization {
    org_id: number,
    owner_id: number,
    ca_crts: string,
    authorized_users: number[],
    name: string
}

export async function list_org(api_key: string): Promise<number[] | string> {
    logger.info(`Getting list of orgs associated with this user`);
    try {
        const resp = await fetch_timeout(`${API_ROOT}/v1/orgs`, {
            'method': 'GET',
            'headers': {
                'Authorization': `Bearer ${api_key}`
            }
        });
        if (!resp.ok) {
            const rawerror = JSON.parse(await resp.text()).errors[0].message;
            logger.error(`error fetching user information: ${rawerror}`);
            return rawerror;
        }
        return JSON.parse(await resp.text()).org_ids;
    } catch (e) {
        logger.error(`Error fetching org list: ${e}`);
        return `${e}`
    }
}

export async function org(org: number, api_key: string): Promise<Organization | string> {
    logger.info(`Getting information about org ${org}`);
    let org_resp: Organization;
    try {
        const resp = await fetch_timeout(`${API_ROOT}/v1/org/${org}`, {
            'method': 'GET',
            'headers': {
                'Authorization': `Bearer ${api_key}`
            }
        });
        if (!resp.ok) {
            const rawerror = JSON.parse(await resp.text()).errors[0].message;
            logger.error(`error fetching user information: ${rawerror}`);
            return rawerror;
        }
        org_resp = JSON.parse(await resp.text()) as Organization;
    } catch (e) {
        logger.error(`Error fetching org list: ${e}`);
        return `${e}`
    }
    logger.info(`Getting user email for ${org_resp.owner_id}`);
    try {
        const resp = await fetch_timeout(`${API_ROOT}/v1/user/${org_resp.owner_id}`, {
            'method': 'GET',
            'headers': {
                'Authorization': `Bearer ${api_key}`
            }
        });
        if (!resp.ok) {
            const rawerror = JSON.parse(await resp.text()).errors[0].message;
            logger.error(`error fetching user information: ${rawerror}`);
            return rawerror;
        }
        org_resp.name = JSON.parse(await resp.text()).email + "'s organization";
    } catch (e) {
        logger.error(`Error fetching owner email: ${e}`);
        return `${e}`
    }
    return org_resp;
}