import * as jwt from 'jsonwebtoken';

export const TEST_SERVICE_JWT_SECRET = 'test-super-secret-service-jwt-key-for-e2e-testing';
export const TEST_ENCRYPTION_KEY = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
export const TEST_ENCRYPTION_KEY_ID = 'test-key-v1';

export function generateServiceToken(
  service: string = 'identity-service',
  secret: string = TEST_SERVICE_JWT_SECRET,
  expiresIn: string = '1h',
): string {
  return jwt.sign(
    { service, iat: Math.floor(Date.now() / 1000) },
    secret,
    { expiresIn },
  );
}

export function generateExpiredServiceToken(
  service: string = 'identity-service',
  secret: string = TEST_SERVICE_JWT_SECRET,
): string {
  return jwt.sign(
    { service, iat: Math.floor(Date.now() / 1000) - 7200, exp: Math.floor(Date.now() / 1000) - 3600 },
    secret,
  );
}

export function generatePublicKey(prefix: string = 'a'): string {
  return '02' + prefix.repeat(64);
}

export function createStoreSharePayload(overrides: Partial<{
  userId: string;
  accountSequence: number;
  publicKey: string;
  encryptedShareData: string;
  threshold: number;
  totalParties: number;
}> = {}) {
  return {
    userId: overrides.userId ?? '12345',
    accountSequence: overrides.accountSequence ?? 1001,
    publicKey: overrides.publicKey ?? generatePublicKey('a'),
    encryptedShareData: overrides.encryptedShareData ?? 'encrypted-share-data-base64',
    threshold: overrides.threshold,
    totalParties: overrides.totalParties,
  };
}

export function createRetrieveSharePayload(overrides: Partial<{
  userId: string;
  publicKey: string;
  recoveryToken: string;
  deviceId: string;
}> = {}) {
  return {
    userId: overrides.userId ?? '12345',
    publicKey: overrides.publicKey ?? generatePublicKey('a'),
    recoveryToken: overrides.recoveryToken ?? 'valid-recovery-token',
    deviceId: overrides.deviceId,
  };
}

export function createRevokeSharePayload(overrides: Partial<{
  userId: string;
  publicKey: string;
  reason: string;
}> = {}) {
  return {
    userId: overrides.userId ?? '12345',
    publicKey: overrides.publicKey ?? generatePublicKey('a'),
    reason: overrides.reason ?? 'ROTATION',
  };
}

export const testEnvConfig = {
  APP_ENV: 'test',
  SERVICE_JWT_SECRET: TEST_SERVICE_JWT_SECRET,
  BACKUP_ENCRYPTION_KEY: TEST_ENCRYPTION_KEY,
  BACKUP_ENCRYPTION_KEY_ID: TEST_ENCRYPTION_KEY_ID,
  MAX_RETRIEVE_PER_DAY: '3',
  ALLOWED_SERVICES: 'identity-service,recovery-service',
};

export function setupTestEnv(): void {
  Object.entries(testEnvConfig).forEach(([key, value]) => {
    process.env[key] = value;
  });
}
