import { Metrics } from "./models/Metrics";
import { SensuMetricStructure } from "./interfaces/sensu";
import { SNSHelpers } from "./aws/sns";
import { ArcanaClient } from "@twitch/arcana";

const arcana = new ArcanaClient();
let api_key: string;

async function getSecret() {
    api_key = api_key || await arcana.decrypt('fastly_key');
}

export default async function handler(event: any, context: any, callback: any) {

    await getSecret();

    if (!api_key) {
      throw new Error("Unable to get API Key")
    }

    let fastlyMetrics = new Metrics(api_key);
    await fastlyMetrics.fillMetrics();

    let metrics: SensuMetricStructure[] = fastlyMetrics.getMetrics().map(m => {
        return m.toSensuPoint();
    })

    if (process.env.IS_LOCAL) {
        console.log(JSON.stringify(metrics, null, 2));
    } else {
        await SNSHelpers.submitToSNS(metrics);
    }
}