import { API } from "../../lib/api.js";
import logging from '../../lib/logging.js';
import assert from 'assert';
import * as queues from "../../lib/queues.js";
import stripe_setup from "stripe";
import { stripe_private } from "../../lib/config.js";

const API_VERSION = stripe_private.api_version;
const log = logging.create("api/payments/stripe_webhook.js");
const hook_q = queues.create("stripe/webhook");
const stripe = stripe_setup(stripe_private.secret);

const validate_stripe = (api) => {
  try {
    assert(stripe_private.endpoint_secret, "Must set endpoint_secret in stripe. The stripe CLI prints this out.");

    const sig = api.req.headers['stripe-signature'];

    const event = stripe.webhooks.constructEvent(api.req.raw_body, sig, stripe_private.endpoint_secret);

    // simulate the api.validate method for now
    event._valid = true;
    return event;
  } catch (err) {
    log.error(err);
    return {_valid: false};
  }
}

export const post = async (req, res) => {
  const api = new API(req, res);

  const msg = validate_stripe(api);

  log.debug(`Stripe WebHook event ${msg.type} ID ${msg.id}`);

  if(msg._valid) {
    assert(msg.api_version == API_VERSION, `Stripe version is ${msg.api_version} but we use ${API_VERSION} created ${msg.created}`);
    hook_q.add(msg);
    api.reply(200, "OK");
  } else {
    api.error(400, "Bad Request");
  }
}

export const get = post;
