'use strict';
const assert = require('assert');
const crypto = require('crypto');
const Server = require('../server.js');

(function run() {
  const original = {
    META_APP_ID: process.env.META_APP_ID,
    META_APP_SECRET: process.env.META_APP_SECRET,
    TIKTOK_CLIENT_KEY: process.env.TIKTOK_CLIENT_KEY,
    TIKTOK_CLIENT_SECRET: process.env.TIKTOK_CLIENT_SECRET,
    GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
    GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET
  };
  process.env.META_APP_ID = 'test-meta-id';
  process.env.META_APP_SECRET = 'test-meta-secret';
  process.env.TIKTOK_CLIENT_KEY = 'test-tiktok-key';
  process.env.TIKTOK_CLIENT_SECRET = 'test-tiktok-secret';
  process.env.GOOGLE_CLIENT_ID = 'test-google-id';
  process.env.GOOGLE_CLIENT_SECRET = 'test-google-secret';

  const providers = Server.oauthProviders();
  assert(providers.facebook.clientId);
  assert.equal(providers.facebook.redirectUri, 'http://127.0.0.1:4173/api/oauth/callback/facebook');
  assert.equal(Object.keys(providers).length, 5);
  assert.equal(providers.tiktok.usesPkce, true);
  assert(providers.youtube_shorts.scope.includes('youtube.upload'));
  assert.equal(providers.youtube_shorts.redirectUri, 'http://127.0.0.1:4173/api/oauth/callback/youtube_shorts');

  const status = Server.oauthPublicStatus(providers.facebook);
  assert.equal(status.configured, true);
  assert.equal(status.connected, false);
  assert(!Object.prototype.hasOwnProperty.call(status, 'clientSecret'));
  assert(!JSON.stringify(status).includes('test-meta-secret'));
  assert(!JSON.stringify(status).includes('test-meta-id'));

  const verifier = 'SHIRE-test-verifier';
  const expected = crypto.createHash('sha256').update(verifier).digest('hex');
  assert.equal(Server.tiktokCodeChallenge(verifier), expected);

  Object.entries(original).forEach(([key, value]) => {
    if (value == null) delete process.env[key];
    else process.env[key] = value;
  });
  console.log('PASS: official OAuth bridge safety tests');
})();
