import { mkdtempSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';

const temp = mkdtempSync(join(tmpdir(), 'vendoo-coolify-'));
process.env.NODE_ENV = 'test';
process.env.VENDOO_DATA_DIR = temp;
process.env.VENDOO_CONFIG_PATH = join(temp, 'config', 'vendoo.env');
process.env.VENDOO_SECRETS_PATH = join(temp, 'config', 'secrets.enc.json');
process.env.VENDOO_MASTER_KEY_FILE = join(temp, 'config', 'master.key');

const failures = [];
const assert = (condition, message) => { if (!condition) failures.push(message); };
let requested = null;
const originalFetch = globalThis.fetch;
globalThis.fetch = async (url, options = {}) => {
  requested = { url: String(url), method: options.method || 'GET', headers: options.headers || {} };
  return new Response(JSON.stringify({ message: 'queued', deployment_uuid: 'test-deployment' }), { status: 200, headers: { 'content-type': 'application/json' } });
};

try {
  const { setSecret } = await import('../lib/secret-store.mjs');
  const { createDeploymentService } = await import('../app/modules/deployments/service.mjs');
  let backupCalls = 0;
  const service = createDeploymentService({
    async createBackup(options) { backupCalls += 1; return { id: 'backup-1', filename: 'pre-deploy.zip', options }; },
    async checkForUpdates() { return { configured: true, current_version: '1.41.2', latest_version: '1.41.3', update_available: true }; },
  });
  setSecret('COOLIFY_DEPLOY_WEBHOOK_URL', 'https://coolify.example.invalid/webhooks/deploy/test', { source: 'test' });
  const status = service.update({
    provider: 'coolify', coolify_url: 'https://coolify.example.invalid', resource_uuid: 'vendoo-test-uuid',
    trigger_mode: 'webhook', deploy_method: 'GET', deploy_endpoint: '/api/v1/deploy?uuid={uuid}&force={force}',
    github_repository: 'Masterluke77/vendoo', github_branch: 'main', ghcr_image: 'ghcr.io/masterluke77/vendoo',
    update_channel: 'stable', backup_before_deploy: true, backup_uploads: false,
  });
  assert(status.configured === true, 'Webhook-Konfiguration wird nicht als vollständig erkannt');
  assert(status.docker_socket_access === false, 'Deployment-Service meldet Docker-Socket-Zugriff');
  const result = await service.trigger({ confirmation: 'DEPLOY', reason: 'test' });
  assert(result.accepted === true, 'Deployment-Auftrag wurde nicht akzeptiert');
  assert(backupCalls === 1, `Vorab-Backup wurde ${backupCalls} Mal ausgeführt`);
  assert(requested?.url === 'https://coolify.example.invalid/webhooks/deploy/test', `Falsche Webhook-URL: ${requested?.url}`);
  assert(requested?.method === 'GET', `Falsche Webhook-Methode: ${requested?.method}`);
  assert(!JSON.stringify(service.status()).includes('webhooks/deploy/test'), 'Webhook-Klarwert wird über Status ausgegeben');
  try { await service.trigger({ confirmation: 'deploy' }); failures.push('Falsche Deployment-Bestätigung wurde akzeptiert'); }
  catch (error) { assert(error.code === 'DEPLOYMENT_CONFIRMATION_REQUIRED', `Falscher Fehlercode für Bestätigung: ${error.code}`); }
  const update = await service.checkUpdates();
  assert(update.update_available === true, 'Updateprüfung wurde nicht delegiert');
} finally {
  globalThis.fetch = originalFetch;
  rmSync(temp, { recursive: true, force: true });
}

if (failures.length) {
  console.error(`Coolify-Deployment-Gate 1.41.2 fehlgeschlagen (${failures.length}):`);
  failures.forEach(item => console.error(`- ${item}`));
  process.exit(1);
}
console.log('Coolify-Deployment-Gate 1.41.2 erfolgreich: verschlüsselte Webhook-Konfiguration, Vorab-Backup, explizite Bestätigung und socketloser Deployment-Auftrag geprüft.');
