import { buildCloudStatusPayload } from './src/server/routes/cloud.js';
import { isCloudUserAuthenticated, sanitizeCloudUser } from './src/cloud/cloud-api.js';

function assert(condition, message) {
  if (!condition) throw new Error(message);
}

console.log('\n── Cloud Auth Guards ──');

const invalidUser = {
  id: 'app',
  code: 203,
  detail: 'Please login first',
  _status: 203,
};

assert(!isCloudUserAuthenticated(invalidUser), '203 login prompt should be treated as logged out');

const rawUser = {
  id: 10007716,
  name: 'mzp@ih5.cn',
  nickName: 'mz',
  companyName: 'ivx',
  picture: '//file.example/avatar.png',
  domain: 'demo.visuallogic.ai',
  status: 1,
  worksCount: 42,
  isPro: true,
  extra: { anthropicKey: 'secret' },
  _setCookie: 'ih5bearer=secret',
  _status: 200,
};

assert(isCloudUserAuthenticated(rawUser), 'valid user payload should be accepted');

const safeUser = sanitizeCloudUser(rawUser);
assert(safeUser.id === rawUser.id, 'sanitized user should keep id');
assert(safeUser.companyName === rawUser.companyName, 'sanitized user should keep company name');
assert(!('extra' in safeUser), 'sanitized user must drop secret extra payload');
assert(!('_setCookie' in safeUser), 'sanitized user must drop cookie data');

const connected = buildCloudStatusPayload(safeUser);
assert(connected.connected === true, 'connected payload should mark connected');
assert(connected.loggedIn === true, 'connected payload should mark logged in');
assert(connected.user?.name === rawUser.name, 'connected payload should include sanitized user');

const loggedOut = buildCloudStatusPayload(null, 'No cookie');
assert(loggedOut.connected === false, 'logged out payload should mark disconnected');
assert(loggedOut.loggedIn === false, 'logged out payload should mark logged out');
assert(loggedOut.error === 'No cookie', 'logged out payload should preserve error');

console.log('PASS test-cloud-auth.js');
