/* test/apiKey.test.js
 *
 * Validates per-service API-key prefix/shape validation in
 * models/apiKey.create().
 */
'use strict';

const assert = require('assert');
const { setupFreshDb, db } = require('./_setup');
const apiKey = require('../models/apiKey');

const TESTS = [];

function test(name, fn) { TESTS.push({ name, fn }); }

test('resend: re_ prefix required', () => {
  setupFreshDb();
  assert.throws(() => apiKey.create({ service: 'resend', key_value: 'notarealkey', label: 't' }), /Resend keys must start with "re_"/);
  assert.throws(() => apiKey.create({ service: 'resend', key_value: 're_short', label: 't' }), /at least 11 chars/);
  const k = apiKey.create({ service: 'resend', key_value: 're_ABCDEFGHIJ1234567890', label: 'good' });
  assert.ok(k.id);
});

test('scrape_do: must be 20+ hex', () => {
  assert.throws(() => apiKey.create({ service: 'scrape_do', key_value: 'nothex!!', label: 't' }), /40-char hex|Scrape\.do keys/);
  const k = apiKey.create({ service: 'scrape_do', key_value: 'abcdef0123456789abcdef0123456789abcdef01', label: 'good' });
  assert.ok(k.id);
});

test('MiniMax: sk- or sk-cp-', () => {
  assert.throws(() => apiKey.create({ service: 'MiniMax', key_value: 'wrong-prefix-1234', label: 't' }), /MiniMax keys/);
  const k1 = apiKey.create({ service: 'MiniMax', key_value: 'sk-cp-test1234', label: 'cp' });
  const k2 = apiKey.create({ service: 'MiniMax', key_value: 'sk-test1234',    label: 'plain' });
  assert.ok(k1.id && k2.id);
});

test('stripe: sk_/pk_/rk_ with optional test_/live_', () => {
  assert.throws(() => apiKey.create({ service: 'stripe', key_value: 'wrong_xxx', label: 't' }), /Stripe keys/);
  const k = apiKey.create({ service: 'stripe', key_value: 'sk_live_TESTKEY1234', label: 'good' });
  assert.ok(k.id);
});

test('safeKey masks key_value', () => {
  const k = apiKey.create({ service: 'resend', key_value: 're_ABCDEFGHIJ1234567890', label: 'mask' });
  const safe = apiKey.safeKey(k);
  assert.strictEqual(safe.key_value, undefined);
  assert.ok(safe.service === 'resend');
});

test('unknown service throws', () => {
  assert.throws(() => apiKey.create({ service: 'totally-fake', key_value: 're_ABC', label: 't' }), /Unknown service/);
});

module.exports = TESTS;
