
import { createMovieProject, createMovieProjectV2, createMovieProjectV3 } from "@/api/create_movie";
import { QueueResponse, withQueuePolling, QueueResponseData } from "@/api/movie_queue";

/**
 * 电影项目创建模式
 */
export enum MovieProjectMode {
  /** 普通模式 */
  NORMAL = "normal",
  /** 照片生成模式 */
  IMAGE = "image",
  /** 模板生成模式 */
  TEMPLATE = "template"
}

/** 创建项目响应数据 */
export interface CreateProjectResponse {
  project_id: string;
}

/**
 * 统一的电影项目创建服务
 */
export class MovieProjectService {
  /**
   * 创建电影项目
   */
  static async createProject<T>(
    mode: MovieProjectMode,
    params: T
  ): Promise<CreateProjectResponse> {
    try {
      let apiCall: (p: T) => Promise<QueueResponse>;

      switch (mode) {
        case MovieProjectMode.NORMAL:
          apiCall = createMovieProject as (p: T) => Promise<QueueResponse>;
          break;
        case MovieProjectMode.IMAGE:
          apiCall = createMovieProjectV2 as (p: T) => Promise<QueueResponse>;
          break;
        case MovieProjectMode.TEMPLATE:
          apiCall = createMovieProjectV3 as (p: T) => Promise<QueueResponse>;
          break;
        default:
          throw new Error(`不支持的创建模式: ${mode}`);
      }

      const result = await withQueuePolling(apiCall, params, {
        interval: 5000,
        maxAttempts: 120,
        onPolling: (data: QueueResponseData) => {
          console.log("轮询状态:", data);
        },
        onError: (error: Error) => {
          if (error.message === '操作已取消') {
            window.msg.info('Queue cancelled');
          } else {
            window.msg.error(error instanceof Error ? error.message : "Failed to create project");
          }
        },
        onCancel: () => {
          window.msg.info('Queue cancelled');
        }
      });

      if (result.code !== 0 && result.code !== 202) {
        throw new Error(result.message || "Failed to create project");
      }

      const projectId = (result.data as any).project_id;
      if (!projectId) {
        throw new Error("Failed to create project: No project ID returned");
      }

      return { project_id: projectId };
    } catch (error) {
      if (error instanceof Error && error.message === '操作已取消') {
        throw error;
      }
      window.msg.error(error instanceof Error ? error.message : "Failed to create project");
      throw error;
    }
  }
}
