#!/usr/bin/env node
/**
 * Push Docker images to registry
 *
 * Usage:
 *   node scripts/push.js              # Push all images
 *   node scripts/push.js app          # Push specific service
 *
 * Environment:
 *   REGISTRY    - Docker registry (default: harbor.gitdata.me/gta_team)
 *   TAG         - Image tag (default: git short SHA)
 *   DOCKER_USER - Registry username
 *   DOCKER_PASS - Registry password
 */

const { execSync } = require('child_process');

const REGISTRY = process.env.REGISTRY || 'harbor.gitdata.me/gta_team';
const GIT_SHA_SHORT = execSync('git rev-parse --short HEAD', {encoding: 'utf8'}).trim();
const TAG = process.env.TAG || GIT_SHA_SHORT;
const DOCKER_USER = process.env.DOCKER_USER || process.env.HARBOR_USERNAME;
const DOCKER_PASS = process.env.DOCKER_PASS || process.env.HARBOR_PASSWORD;

const SERVICES = ['app', 'gitserver', 'email-worker', 'git-hook', 'operator', 'static', 'frontend'];

const args = process.argv.slice(2);
const targets = args.length > 0 ? args : SERVICES;

if (!DOCKER_USER || !DOCKER_PASS) {
  console.error('Error: DOCKER_USER and DOCKER_PASS environment variables are required');
  console.error('Set HARBOR_USERNAME and HARBOR_PASSWORD as alternative');
  process.exit(1);
}

console.log(`\n=== Push Configuration ===`);
console.log(`Registry: ${REGISTRY}`);
console.log(`Tag: ${TAG}`);
console.log(`Services: ${targets.join(', ')}\n`);

// Login
console.log(`==> Logging in to ${REGISTRY}`);
try {
  execSync(`docker login ${REGISTRY} -u "${DOCKER_USER}" -p "${DOCKER_PASS}"`, {
    stdio: 'inherit'
  });
} catch (error) {
  console.error('Login failed');
  process.exit(1);
}

for (const service of targets) {
  if (!SERVICES.includes(service)) {
    console.error(`Unknown service: ${service}`);
    process.exit(1);
  }

  const image = `${REGISTRY}/${service}:${TAG}`;

  console.log(`\n==> Pushing ${image}`);

  try {
    execSync(`docker push "${image}"`, { stdio: 'inherit' });
    console.log(`    [OK] ${image}`);
  } catch (error) {
    console.error(`    [FAIL] ${service}`);
    process.exit(1);
  }
}

console.log(`\n=== Push Complete ===`);
console.log('');
