import { apiClient } from './client';
import { RunTemplateResponse, TemplateGenerationResponse, RunTemplateData } from '../types/template-run';

export async function runTemplate(
  templateId: string,
  data: RunTemplateData,
  identifier: string
): Promise<RunTemplateResponse> {
  // identifier 是必需的支付凭证，如果没有提供说明支付失败
  if (!identifier) {
    throw new Error('支付凭证缺失，无法创建生成任务');
  }

  return apiClient<RunTemplateResponse>(`/api/templates/${templateId}/run`, {
    method: 'POST',
    body: JSON.stringify({
      data,
      identifier,
    }),
  });
}

export async function getTemplateGeneration(generationId: string): Promise<TemplateGenerationResponse> {
  return apiClient<TemplateGenerationResponse>(`/api/template-generations/${generationId}`);
}

export async function pollTemplateGeneration(
  generationId: string,
  onComplete: (result: any) => void,
  onError: (error: Error) => void,
  maxAttempts: number = 100,
  intervalMs: number = 3000
): Promise<void> {
  let attempts = 0;

  const poll = async () => {
    try {
      attempts++;

      if (attempts > maxAttempts) {
        throw new Error('轮询超时，请稍后重试');
      }

      const response = await getTemplateGeneration(generationId);
      const generation = response.data;

      // 检查是否完成
      if (generation.status === 'completed') {
        onComplete(generation);
        return;
      }

      // 检查是否失败
      if (generation.status === 'failed') {
        throw new Error('任务执行失败');
      }

      // 继续轮询
      setTimeout(poll, intervalMs);

    } catch (error) {
      onError(error as Error);
    }
  };

  // 开始轮询
  setTimeout(poll, intervalMs);
}