#!/usr/bin/env node
import assert from 'assert';
import express from 'express';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { setupWorkspaceRoutes } from './src/server/routes/workspace.js';
import { VL_CODE_HOME } from './src/server/helpers.js';

const WORKSPACES_FILE = path.join(VL_CODE_HOME, 'workspaces.json');

async function main() {
  const parentDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vlcode-route-parent-'));
  const backup = fs.existsSync(WORKSPACES_FILE)
    ? fs.readFileSync(WORKSPACES_FILE, 'utf8')
    : null;

  const app = express();
  app.use(express.json({ limit: '10mb' }));

  const fakeServer = {
    config: {
      emptyWorkspaceDir: path.join(os.tmpdir(), 'vlcode-empty-window-route-test'),
    },
    _openTabs: [],
    _workspaceStates: new Map(),
    _saveOpenTabs() {},
    broadcast() {},
    hasSelectedWorkspace() { return false; },
    getVisibleWorkDir() { return ''; },
    async switchWorkspace() { return { ok: true }; },
  };

  setupWorkspaceRoutes(app, fakeServer);
  const httpServer = app.listen(0);
  await new Promise((resolve, reject) => {
    httpServer.once('listening', resolve);
    httpServer.once('error', reject);
  });
  const { port } = httpServer.address();

  try {
    const response = await fetch(`http://127.0.0.1:${port}/api/workspaces/create-project`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        projectName: 'RouteCreateProjectTest',
        parentDir,
      }),
    });
    const body = await response.json();

    assert.equal(response.status, 200);
    assert.equal(body.ok, true);
    const projectDir = path.join(parentDir, 'RouteCreateProjectTest');
    assert.ok(fs.existsSync(path.join(projectDir, '.vl-code', 'project.json')));
    assert.ok(fs.existsSync(path.join(projectDir, '.vl-code', 'workflows', 'parallel-codegen.json')));
    assert.ok(fs.existsSync(path.join(projectDir, 'Theme', 'Theme.vth')));
  } finally {
    await new Promise((resolve) => httpServer.close(resolve));
    fs.rmSync(parentDir, { recursive: true, force: true });
    if (backup === null) fs.rmSync(WORKSPACES_FILE, { force: true });
    else fs.writeFileSync(WORKSPACES_FILE, backup, 'utf8');
  }

  console.log('\n── Workspace Create Project Route ──');
  console.log('PASS test-workspace-create-project-route.js');
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
