import assert from 'node:assert/strict';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import test from 'node:test';

const repoRoot = join(process.cwd(), '../..');

test('production Dockerfiles embed runtime version metadata', () => {
  const webDockerfile = readFileSync(join(repoRoot, 'Dockerfile.web'), 'utf8');
  const serverDockerfile = readFileSync(join(repoRoot, 'Dockerfile.server'), 'utf8');

  assert.match(webDockerfile, /ARG APP_VERSION=unknown/);
  assert.match(webDockerfile, /ENV NEXT_PUBLIC_APP_VERSION=\$APP_VERSION/);
  assert.match(serverDockerfile, /ARG APP_VERSION=unknown/);
  assert.match(serverDockerfile, /ENV APP_VERSION=\$APP_VERSION/);
});

test('production compose can pull immutable web and server images', () => {
  const compose = readFileSync(join(repoRoot, 'docker-compose.prod.yml'), 'utf8');

  assert.match(compose, /image: \$\{SERVER_IMAGE:\?Set SERVER_IMAGE/);
  assert.match(compose, /image: \$\{WEB_IMAGE:\?Set WEB_IMAGE/);
  assert.match(compose, /APP_VERSION: \$\{APP_VERSION:-unknown\}/);
});

test('GitHub Actions workflow builds pushes deploys migrates and verifies runtime version', () => {
  const workflowPath = join(repoRoot, '.github/workflows/deploy-production.yml');
  assert.equal(existsSync(workflowPath), true);
  const workflow = readFileSync(workflowPath, 'utf8');
  const smokeScript = readFileSync(join(repoRoot, 'scripts/smoke-test-release.mjs'), 'utf8');

  assert.match(workflow, /docker\/build-push-action/);
  assert.match(workflow, /appleboy\/ssh-action/);
  assert.match(workflow, /docker compose --env-file \.env\.production -f docker-compose\.prod\.yml pull/);
  assert.match(workflow, /pnpm --filter server db:deploy/);
  assert.match(workflow, /smoke-test-release\.mjs/);
  assert.match(workflow, /--expected-version "\$\{\{ github\.sha \}\}"/);
  assert.match(smokeScript, /\/api\/v1\/health\/version/);
});

test('deployment runtime version check is available as a repeatable script', () => {
  const packageJson = readFileSync(join(repoRoot, 'package.json'), 'utf8');

  assert.equal(existsSync(join(repoRoot, 'scripts/check-runtime-version.mjs')), true);
  assert.match(packageJson, /"deploy:check-runtime": "node scripts\/check-runtime-version\.mjs"/);
});
