#!/usr/bin/env node
/**
 * Push Admin Docker image to registry
 *
 * Usage:
 *   node scripts/push.js              # Push image
 *   node scripts/push.js --dry-run   # Show what would be pushed
 *
 * 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 path = require('path');

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 SERVICE = 'admin';
const DOCKER_USER = process.env.DOCKER_USER || process.env.HARBOR_USERNAME;
const DOCKER_PASS = process.env.DOCKER_PASS || process.env.HARBOR_PASSWORD;

const args = process.argv.slice(2);
const isDryRun = args.includes('--dry-run');

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);
}

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

console.log(`\n=== Push Configuration ===`);
console.log(`Registry: ${REGISTRY}`);
console.log(`Tag: ${TAG}`);
console.log(`Image: ${image}`);
console.log(`Dry Run: ${isDryRun}`);
console.log('');

if (isDryRun) {
  console.log('[DRY RUN] Would push:', image);
  console.log('');
  process.exit(0);
}

// 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);
}

// Push
console.log(`\n==> Pushing ${image}`);
try {
  execSync(`docker push "${image}"`, { stdio: 'inherit' });
  console.log(`    [OK] ${image}`);
} catch (error) {
  console.error(`    [FAIL] Push failed`);
  process.exit(1);
}

console.log(`\n=== Push Complete ===`);
console.log(`  ${image}`);
console.log('');
