// POST /api/license/verify {key} → {ok, token, expires_at} ou {ok:false, reason}
const { verifyKey, issueToken, readBody, json, TOKEN_TTL_S } = require('../_lib');

module.exports = async (req, res) => {
  if (req.method === 'OPTIONS') return json(res, 204, {});
  if (req.method !== 'POST') return json(res, 405, { ok: false, reason: 'use POST' });
  const body = await readBody(req);
  const key = (body.key || '').trim();
  if (!key) return json(res, 400, { ok: false, reason: 'key ausente' });
  const v = verifyKey(key);
  if (!v.ok) return json(res, 403, { ok: false, reason: v.reason, expires_at: v.expires_at || null });
  const tok = issueToken(key);
  return json(res, 200, {
    ok: true,
    token: tok,
    token_ttl_s: TOKEN_TTL_S,
    expires_at: v.expires_at,
    owner_id: v.owner_id,
  });
};
