import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { randomUUID } from 'node:crypto';
import { Repository } from './repository.js';

function freshRepo() {
  const dir = mkdtempSync(join(tmpdir(), 'runtime-dir-'));
  const repo = new Repository(join(dir, `${randomUUID()}.db`));
  return { repo, dir };
}

describe('runtime_dir column (計画5 Phase A)', () => {
  let repo: Repository; let dir: string;
  beforeEach(() => { ({ repo, dir } = freshRepo()); });
  afterEach(() => { rmSync(dir, { recursive: true, force: true }); });

  it('local_tasks and jobs have a runtime_dir column', () => {
    for (const t of ['local_tasks', 'jobs']) {
      // @ts-expect-error private db handle
      const cols = repo.db.prepare(`PRAGMA table_info('${t}')`).all() as Array<{ name: string }>;
      expect(cols.map(c => c.name)).toContain('runtime_dir');
    }
  });

  it('createLocalTask defaults runtimeDir to null (後方互換)', async () => {
    const task = await repo.createLocalTask({ title: 't', body: 'b', ownerId: 'u1' });
    expect(task.runtimeDir).toBeNull();
    const loaded = await repo.getLocalTask(task.id);
    expect(loaded?.runtimeDir).toBeNull();
  });

  it('updateLocalTask persists and reads back runtimeDir', async () => {
    const task = await repo.createLocalTask({ title: 't', body: 'b', ownerId: 'u1' });
    const runtimeDir = '/tmp/space/abc/runs/' + task.id;
    await repo.updateLocalTask(task.id, { runtimeDir });
    const loaded = await repo.getLocalTask(task.id);
    expect(loaded?.runtimeDir).toBe(runtimeDir);
  });

  it('createJob round-trips runtimeDir (default null + explicit value)', async () => {
    const j1 = await repo.createJob({ repo: 'local/task-1', issueNumber: 1, instruction: 'go' });
    expect(j1.runtimeDir).toBeNull();

    const rd = '/tmp/space/abc/runs/2';
    const j2 = await repo.createJob({ repo: 'local/task-2', issueNumber: 2, instruction: 'go', runtimeDir: rd });
    expect(j2.runtimeDir).toBe(rd);
  });
});
