import { describe, it, expect } from 'vitest';
import { resolveRootJobId } from './worker.js';

const repo = (jobs: Record<string, any>) => ({ getJob: async (id: string) => jobs[id] ?? null } as any);

describe('resolveRootJobId', () => {
  it('local task 直接ジョブは自分の id を返す', async () => {
    const job = { id: 'J1', repo: 'local/task-7', parentJobId: null } as any;
    expect(await resolveRootJobId(repo({}), job)).toBe('J1');
  });

  it('サブタスクは local task の最上位ジョブ id を返す', async () => {
    const root = { id: 'ROOT', repo: 'local/task-7', parentJobId: null };
    const sub = { id: 'SUB', repo: 'subtask/' + '0'.repeat(36), parentJobId: 'ROOT' } as any;
    expect(await resolveRootJobId(repo({ ROOT: root }), sub)).toBe('ROOT');
  });

  it('2段ネストのサブタスクは root local task id を返す', async () => {
    const root = { id: 'ROOT', repo: 'local/task-3', parentJobId: null };
    const mid = { id: 'MID', repo: 'subtask/' + 'a'.repeat(36), parentJobId: 'ROOT' };
    const leaf = { id: 'LEAF', repo: 'subtask/' + 'b'.repeat(36), parentJobId: 'MID' } as any;
    expect(await resolveRootJobId(repo({ ROOT: root, MID: mid }), leaf)).toBe('ROOT');
  });

  it('親が見つからない場合は最後に確認した id を返す', async () => {
    const sub = { id: 'SUB', repo: 'subtask/' + '0'.repeat(36), parentJobId: 'MISSING' } as any;
    // MISSING は repo に存在しない → last = 'MISSING' を返す
    expect(await resolveRootJobId(repo({}), sub)).toBe('MISSING');
  });

  it('parentJobId のない非 local-task ジョブは undefined を返す', async () => {
    // gitea issue ジョブ等: repo 名が local/task-N でも subtask/ でもない
    const job = { id: 'GH1', repo: 'some/repo', parentJobId: null } as any;
    expect(await resolveRootJobId(repo({}), job)).toBeUndefined();
  });
});
