import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AiA2uiSubmission } from './entities/ai-a2ui-submission.entity';

export interface RecordSubmissionInput {
  artifactId: string;
  clientRequestId: string;
  status: string;
  resultJson?: string | null;
}

/**
 * A2UI 提交幂等服务。
 */
@Injectable()
export class A2uiSubmissionsService {
  constructor(
    @InjectRepository(AiA2uiSubmission)
    private readonly submissions: Repository<AiA2uiSubmission>,
  ) {}

  async recordSubmission(input: RecordSubmissionInput): Promise<{
    created: boolean;
    submission: AiA2uiSubmission;
  }> {
    const existing = await this.findSubmission(input.artifactId, input.clientRequestId);
    if (existing) return { created: false, submission: existing };
    const submission = await this.submissions.save(
      this.submissions.create({
        artifactId: input.artifactId,
        clientRequestId: input.clientRequestId,
        status: input.status,
        resultJson: input.resultJson ?? null,
      }),
    );
    return { created: true, submission };
  }

  async findSubmission(
    artifactId: string,
    clientRequestId: string,
  ): Promise<AiA2uiSubmission | null> {
    return this.submissions.findOne({
      where: { artifactId, clientRequestId },
    });
  }
}
