import type { BlockSchema } from '@vtj/core';

import instance from './instance';

export type LowCodeFileSchema = {
  active: boolean;
  dsl: BlockSchema;
  file_id?: string;
  file_path?: string;
  project_id: number;
  publish: boolean;
  published_dsl: BlockSchema;
};

function transformFile(file: LowCodeFileSchema): LowCodeFileSchema {
  return {
    project_id: file.project_id,
    publish: file.publish,
    active: file.active,
    // @ts-ignore
    dsl: JSON.stringify(file.dsl),
    file_path: file.file_path,
    file_id: file.file_id
  };
}

export const getFileList = async () => {
  const response = await instance.get('/api/v1/files');
  return response.data;
};

export const getFile = async (id: string) => {
  const response = await instance.get(`/api/v1/files/${id}`);
  return response.data;
};

export const createFile = async (data: LowCodeFileSchema) => {
  const response = await instance.post('/api/v1/files', transformFile(data));
  return response.data;
};

export const updateFile = async (id: string, data: LowCodeFileSchema) => {
  const response = await instance.put(
    `/api/v1/files/${id}`,
    transformFile(data)
  );
  return response.data;
};

type PublishResponse = {
  code: string;
  data: object;
  id?: string;
  message: string;
};

export const deleteFile = async (id: string) => {
  const response = await instance.delete(`/api/v1/files/${id}`);
  return response.data;
};

/**
 * 发布指定项目的所有文件
 * @param {number} projectId - 需要发布的项目ID
 * @returns {Promise<any>} 包含发布操作结果的Promise对象
 * @example
 * // 发布项目ID为123的所有文件
 * await publishAllFile(123)
 */
export const publishAllFile = async (
  projectId: number
): Promise<PublishResponse> => {
  const response = await instance.post('/api/v1/files/publish', {
    project_id: projectId
  });
  return response.data;
};

/**
 * 发布单个文件
 * @param {string} fileId - 需要发布的文件ID
 * @returns {Promise<any>} 包含发布操作结果的Promise对象
 */
export const publishFile = async (fileId: string): Promise<PublishResponse> => {
  const response = await instance.post('/api/v1/files/publish-file', {
    file_id: fileId
  });
  return response.data;
};
