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

import instance from './instance';

export type LowCodeHistorySchema = {
  dsl?: HistorySchema;
  file_id: string;
  history_id: string;
  id?: string;
  project_id: number;
};

function transformHistoryData(data: LowCodeHistorySchema) {
  return {
    ...data,
    dsl: JSON.stringify(data.dsl || {})
  };
}

export type HistoriesResponse = {
  code: number;
  data: {
    list: Array<{
      created_at: string;
      dsl: Record<string, any>;
      file_id: string;
      history_id: string;
      id: number;
      project_id: number;
      updated_at: string;
    }>;
    total: number;
  };
  message: string;
};

export type GetHistoriesParams = {
  file_id: string;
  page?: number;
  per_page?: number;
  project_id: number;
};

export const getHistories = async (params: GetHistoriesParams) => {
  const response = await instance.get<HistoriesResponse>('/api/v1/histories', {
    params: {
      project_id: params.project_id,
      file_id: params.file_id,
      ...(params.page && { page: params.page }),
      ...(params.per_page && { per_page: params.per_page })
    }
  });
  return response.data;
};

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

export const createHistory = async (data: LowCodeHistorySchema) => {
  const response = await instance.post(
    '/api/v1/histories',
    transformHistoryData(data)
  );
  return response.data;
};

export const updateHistory = async (id: string, data: any) => {
  const response = await instance.put(`/api/v1/histories/${id}`, data);
  return response.data;
};

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