// POST /api/admin/issue {owner, days} [header x-admin-password] → {key, expires_at}
const { genKey, requireAdmin, readBody, json } = 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' });
  if (!requireAdmin(req)) return json(res, 401, { ok: false, reason: 'unauthorized' });
  const body = await readBody(req);
  const owner = String(body.owner || '').trim();
  const ownerId = String(body.owner_id || '').trim().toLowerCase();
  const days = parseInt(body.days || 30, 10);
  if (!owner && !ownerId) return json(res, 400, { ok: false, reason: 'owner ou owner_id ausente' });
  if (!days || days < 1 || days > 3650) return json(res, 400, { ok: false, reason: 'days inválido (1–3650)' });
  const expiresTs = Math.floor(Date.now() / 1000) + days * 86400;
  const key = genKey(owner || ownerId, expiresTs, ownerId);
  return json(res, 200, { ok: true, key, owner: owner || ownerId, expires_at: expiresTs, days });
};
