import { existsSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';

import { describe, expect, it } from 'vitest';

function readViewSource(relativePath: string) {
  const workspaceViews = resolve('app/src/views');
  const viewsRoot = existsSync(workspaceViews)
    ? workspaceViews
    : resolve('src/views');
  return readFileSync(resolve(viewsRoot, relativePath), 'utf8');
}

describe('detail return navigation', () => {
  it.each([
    [
      'ai/documentCollection/DocumentCollection.vue',
      'ai/documentCollection/Document.vue',
    ],
    ['ai/skill/SkillList.vue', 'ai/skill/SkillDetail.vue'],
    ['ai/agents/AgentList.vue', 'ai/agents/AgentDesigner.vue'],
    ['ai/bots/index.vue', 'ai/bots/pages/setting/index.vue'],
    [
      'system/approval/ApprovalManage.vue',
      'system/approval/ApprovalDetail.vue',
    ],
    ['system/sysJob/SysJobList.vue', 'system/sysJob/SysJobLogList.vue'],
    [
      'system/sysFeedback/sysFeedbackList.vue',
      'system/sysFeedback/sysFeedbackDetail.vue',
    ],
    ['ai/workflow/WorkflowList.vue', 'ai/workflow/WorkflowDesign.vue'],
    [
      'ai/workflow/WorkflowList.vue',
      'ai/workflow/components/WorkflowChatPage.vue',
    ],
    ['ai/plugin/Plugin.vue', 'ai/plugin/PluginTools.vue'],
    ['ai/plugin/PluginToolTable.vue', 'ai/plugin/PluginToolEdit.vue'],
  ])(
    'passes an exact return target from %s and validates it in %s',
    (listPath, detailPath) => {
      expect(readViewSource(listPath)).toContain('withListReturnTo');
      expect(readViewSource(detailPath)).toContain('navigateBackToList');
    },
  );

  it('preserves the nested execution-record list before opening a step', () => {
    const recordSource = readViewSource(
      'ai/workflow/execute/WorkflowExecResultList.vue',
    );
    const stepSource = readViewSource(
      'ai/workflow/execute/WorkflowExecStepList.vue',
    );

    expect(recordSource).toContain('withListReturnTo(currentListFullPath())');
    expect(stepSource).toContain('navigateBackToList');
    expect(stepSource).toContain("['/ai/workflow/executeRecords']");
  });
});
