#!/usr/bin/env node
/**
 * Build Docker image for Admin
 *
 * Workflow:
 *   1. npm ci --legacy-peer-deps   (install dependencies)
 *   2. npm run build                (Next.js build, outputs to .next/)
 *   3. docker build                  (multi-stage, minimal runtime image)
 *
 * Usage:
 *   node scripts/build.js            # Build image
 *   node scripts/build.js --no-cache  # Build without Docker layer cache
 *
 * Environment:
 *   REGISTRY  - Docker registry (default: harbor.gitdata.me/gta_team)
 *   TAG       - Image tag (default: git short SHA)
 */

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 args = process.argv.slice(2);
const noCache = args.includes('--no-cache');
const rootDir = path.join(__dirname, '..');

console.log(`\n=== Build Configuration ===`);
console.log(`Registry: ${REGISTRY}`);
console.log(`Tag: ${TAG}`);
console.log(`Service: ${SERVICE}`);
console.log(`No Cache: ${noCache}`);
console.log('');

// Step 1: npm ci
console.log(`==> Step 1: Installing dependencies (npm ci)`);
try {
  execSync(`npm ci --legacy-peer-deps`, {
    stdio: 'inherit',
    cwd: rootDir,
  });
  console.log(`    [OK] Dependencies installed`);
} catch (error) {
  console.error(`    [FAIL] npm ci failed`);
  process.exit(1);
}

// Step 2: Next.js build
console.log(`\n==> Step 2: Building Next.js (npm run build)`);
try {
  execSync(`npm run build`, {
    stdio: 'inherit',
    cwd: rootDir,
    env: { ...process.env, NEXT_TELEMETRY_DISABLED: '1' },
  });
  console.log(`    [OK] Next.js build complete`);
} catch (error) {
  console.error(`    [FAIL] Next.js build failed`);
  process.exit(1);
}

// Step 3: Docker build
console.log(`\n==> Step 3: Building Docker image`);
const dockerfile = path.join(rootDir, 'Dockerfile');
const image = `${REGISTRY}/${SERVICE}:${TAG}`;
const buildCmd = `docker build ${noCache ? '--no-cache' : ''} -f "${dockerfile}" -t "${image}" .`;

console.log(`    Building ${image}`);
try {
  execSync(buildCmd, { stdio: 'inherit', cwd: rootDir });
  console.log(`    [OK] ${image}`);
} catch (error) {
  console.error(`    [FAIL] Docker build failed`);
  process.exit(1);
}

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