import { describe, expect, it, jest } from '@jest/globals';
import { A2uiSubmissionsService } from './ai-a2ui-submissions.service';

function createService(overrides: Record<string, unknown> = {}) {
  const repo = {
    findOne: jest.fn(),
    save: jest.fn(async (value) => value),
    create: jest.fn((value) => value),
    ...overrides,
  };
  return { service: new A2uiSubmissionsService(repo as never), repo };
}

const submission = {
  id: 1,
  artifactId: 'form-1',
  clientRequestId: '4d5c1c2a-1111-4222-8333-444455556666',
  status: 'created',
  resultJson: '{"ok":true}',
  createdAt: new Date(),
};

describe('A2uiSubmissionsService', () => {
  it('recordSubmission 首次提交创建记录并标记 created', async () => {
    const { service, repo } = createService({
      findOne: jest.fn().mockResolvedValue(null),
    });
    const result = await service.recordSubmission({
      artifactId: submission.artifactId,
      clientRequestId: submission.clientRequestId,
      status: 'created',
      resultJson: submission.resultJson,
    });
    expect(result.created).toBe(true);
    expect(repo.save).toHaveBeenCalledWith(
      expect.objectContaining({
        artifactId: submission.artifactId,
        clientRequestId: submission.clientRequestId,
      }),
    );
  });

  it('recordSubmission 同一 clientRequestId 重复提交返回既有记录且不重复创建', async () => {
    const { service, repo } = createService({
      findOne: jest.fn().mockResolvedValue(submission),
    });
    const result = await service.recordSubmission({
      artifactId: submission.artifactId,
      clientRequestId: submission.clientRequestId,
      status: 'created',
      resultJson: '{"ok":false}',
    });
    expect(result.created).toBe(false);
    expect(result.submission).toEqual(submission);
    expect(repo.save).not.toHaveBeenCalled();
  });

  it('findSubmission 透传查询条件', async () => {
    const { service, repo } = createService({
      findOne: jest.fn().mockResolvedValue(submission),
    });
    await expect(
      service.findSubmission(submission.artifactId, submission.clientRequestId),
    ).resolves.toEqual(submission);
    expect(repo.findOne).toHaveBeenCalledWith({
      where: { artifactId: submission.artifactId, clientRequestId: submission.clientRequestId },
    });
  });
});
