import logging from "../lib/logging.js";
import assert from "assert";
import { API } from "../lib/api.js";
import { Payment, Product } from "../lib/models.js";

const log = logging.create(import.meta.url);

export const get = async (req, res) => {
  const api = new API(req, res);
  const { product_id } = req.query;
  assert(product_id != undefined, "product_id is required.");

  try {
    const product = await Product.first({id: product_id});
    assert(product, `Product is not found ${product_id}`);

    const [paid, payment] = await Payment.paid(api.user);

    if(!paid) {
      // TODO: We need to return the product to pay...is there
      // a better way to do this maybe?
      api.error(402, {payment, product});
    } else {
      api.reply(200, product);
    }
  } catch (error) {
    log.error(error);
    api.error(500, "Internal Server Error");
  }
}

get.authenticated = true;
