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

import {
  buildWorkflowRunDraftKey,
  hasWorkflowRunDraftContent,
  readWorkflowRunDraft,
  removeWorkflowRunDraft,
  WORKFLOW_RUN_DRAFT_TTL_MS,
  writeWorkflowRunDraft,
} from '../workflowRunDraft';

const parameters = [
  { contentType: 'text', formType: 'input', name: 'company' },
  { contentType: 'file', formType: 'input', name: 'attachment' },
];

describe('workflowRunDraft', () => {
  beforeEach(() => {
    sessionStorage.clear();
  });

  it('isolates drafts by workflow, account and run mode', () => {
    expect(buildWorkflowRunDraftKey('flow-1', 'tenant:user-1', false)).not.toBe(
      buildWorkflowRunDraftKey('flow-1', 'tenant:user-2', false),
    );
    expect(buildWorkflowRunDraftKey('flow-1', 'tenant:user-1', false)).not.toBe(
      buildWorkflowRunDraftKey('flow-2', 'tenant:user-1', false),
    );
    expect(buildWorkflowRunDraftKey('flow-1', 'tenant:user-1', true)).not.toBe(
      buildWorkflowRunDraftKey('flow-1', 'tenant:user-1', false),
    );
  });

  it('restores current compatible fields within twelve hours', () => {
    const key = buildWorkflowRunDraftKey('flow-1', 'tenant:user-1', false);
    writeWorkflowRunDraft(
      sessionStorage,
      key,
      {
        question: '分析合同',
        values: {
          attachment: [{ name: 'contract.pdf', url: '/contract.pdf' }],
          company: '华北分公司',
          removedField: '旧字段',
        },
      },
      1000,
    );

    expect(readWorkflowRunDraft(sessionStorage, key, parameters, 2000)).toEqual(
      {
        question: '分析合同',
        values: {
          attachment: [{ name: 'contract.pdf', url: '/contract.pdf' }],
          company: '华北分公司',
        },
      },
    );
  });

  it('drops expired drafts', () => {
    const key = buildWorkflowRunDraftKey('flow-1', 'tenant:user-1', false);
    writeWorkflowRunDraft(
      sessionStorage,
      key,
      {
        question: '过期内容',
        values: { attachment: '错误文件值', company: ['错误文本值'] },
      },
      1000,
    );

    expect(
      readWorkflowRunDraft(
        sessionStorage,
        key,
        parameters,
        1000 + WORKFLOW_RUN_DRAFT_TTL_MS,
      ),
    ).toBeUndefined();
    expect(sessionStorage.getItem(key)).toBeNull();
  });

  it('only persists user changes and supports an explicit reset', () => {
    const defaults = { attachment: [], company: '' };
    expect(hasWorkflowRunDraftContent('', defaults, defaults)).toBe(false);
    expect(
      hasWorkflowRunDraftContent(
        '',
        { ...defaults, company: '华北' },
        defaults,
      ),
    ).toBe(true);
    expect(hasWorkflowRunDraftContent('待处理', defaults, defaults)).toBe(true);

    const key = buildWorkflowRunDraftKey('flow-1', 'tenant:user-1', false);
    writeWorkflowRunDraft(sessionStorage, key, {
      question: '待处理',
      values: defaults,
    });
    removeWorkflowRunDraft(sessionStorage, key);
    expect(sessionStorage.getItem(key)).toBeNull();
  });
});
