import { createAsyncThunk } from '@reduxjs/toolkit';
import Api from '@/api';

export interface AdvancedReportsDataSQL {
  fields: Object;
  tables: Object;
  filters: [];
  groupby: [];
  orderby: [];
  SQLSTRING: string;
}

export interface AdvancedReportsData {
  SQL: AdvancedReportsDataSQL;
}

export interface SaveReportRequest {
  id?: number;
  report_title: string;
  type: string;
  search_name: string;
  reportCategory: string;
  search_url: string;
  search_params: string;
  overwrite: boolean;
  sharedPermission: Object;
  AdvancedReportsData: AdvancedReportsData;
  is_public: boolean;
}

export const saveReport = createAsyncThunk(
  'users/saveReport',
  async (report: SaveReportRequest, { rejectWithValue }) => {
    const formData = new FormData();

    for (var key in report) {
      const value = typeof report[key] === 'string' ? report[key] : JSON.stringify(report[key]);
      formData.append(key, value);
    }

    formData.delete('AdvancedReportsData');
    formData.append('AdvancedReportsData[SQL]', JSON.stringify(report.AdvancedReportsData.SQL));
    formData.set('search_params', encodeURIComponent(report.search_params));

    try {
      const { data } = await Api.post(
        '/advancedreports/save',
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
          }
        }
      );
      notify.success('Report successfully saved.');
      return data;
    } catch (error) {
      return rejectWithValue(error.response?.data || {});
    }
  }
);
