import fs from 'node:fs';
import http from 'node:http';

function requestDocker(socketPath, requestPath, method) {
  return new Promise((resolve, reject) => {
    const request = http.request(
      {
        socketPath,
        path: requestPath,
        method,
      },
      (response) => {
        let body = '';
        response.setEncoding('utf8');
        response.on('data', (chunk) => {
          body += chunk;
        });
        response.on('end', () => {
          resolve({
            statusCode: response.statusCode ?? 500,
            body,
          });
        });
      },
    );

    request.on('error', reject);
    request.end();
  });
}

async function main() {
  const containerName = process.argv[2]?.trim();
  const socketPath = process.env.SERVER_COMMAND_DOCKER_SOCKET?.trim() || '/var/run/docker.sock';

  if (!containerName) {
    console.error('container name is required');
    process.exit(1);
  }

  if (!fs.existsSync(socketPath)) {
    console.error(`Docker socket not found: ${socketPath}`);
    process.exit(127);
  }

  const restartPath = `/containers/${encodeURIComponent(containerName)}/restart?t=30`;
  const response = await requestDocker(socketPath, restartPath, 'POST');

  if (response.statusCode >= 200 && response.statusCode < 300) {
    process.stdout.write(`${containerName} restarted via Docker socket`);
    return;
  }

  if (response.statusCode === 404) {
    console.error(`Container not found: ${containerName}`);
    process.exit(1);
  }

  console.error(`Docker socket restart failed (${response.statusCode}): ${response.body.trim()}`);
  process.exit(1);
}

await main();
