import logging from "../lib/logging.js";
import { API } from "../lib/api.js";
import assert from "assert";
import { User } from "../lib/models.js";

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

const rules = {
  unsubkey: "required|alpha_num"
}

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

  try {
    const form = api.validate(rules);

    if(form._valid) {
      const user = await User.first({unsubkey: form.unsubkey});

      if(!user) {
        return api.error(404, "User not found.");
      } else {
        const res = await user.emails(false);
        assert(res === 1, `Invalid update returned ${res}`);
        return api.reply(200, {message: "OK"});
      }
    } else {
      return api.validation_error(res, form);
    }
  } catch (error) {
    log.error(error);
    return api.error(500, "Internal Server Error");
  }
}
