import { BaseDataManager } from './baseDataManager';
import { DATE_TIME_FORMAT } from '../constants/define';
import { convertCamelCaseToSnakeCase, convertDateToString } from '../utilities/functions';
import { uniqueId } from 'lodash';

export default class JobDataManager extends BaseDataManager {
  static formatRequestObject(job) {
    const { url, name, county, startDate, endDate, actionCode, orderBy, ...rest } = job || {};

    return {
      ...rest,
      url,
      name,
      county,
      startDate,
      endDate,
      actionCode: JSON.stringify(actionCode),
      ...(startDate ? { startDate: convertDateToString(startDate, DATE_TIME_FORMAT.SHORT_DATE_EXPORT) } : {}),
      ...(endDate ? { endDate: convertDateToString(endDate, DATE_TIME_FORMAT.SHORT_DATE_EXPORT) } : {}),
      ...(orderBy?.id && { orderBy: `${orderBy?.desc ? '-' : ''}${convertCamelCaseToSnakeCase(orderBy?.id)}` }),
    };
  }

  static formatResponseObject(job) {
    const { actionCode, startDate, endDate, createdAt, updatedAt, ...rest } = job;

    let parsedActionCode = [];
    if (typeof actionCode === 'string') {
      try {
        parsedActionCode = JSON.parse(actionCode);
        // if (Array.isArray(parsedActionCode)) {
        //   parsedActionCode = parsedActionCode.map((item) => {
        //     return {
        //       id: uniqueId(),
        //       ...item,
        //     };
        //   });
        // }
      } catch (error) {
        console.error('Failed to parse actionCode:', error);
        // Handle error as appropriate for your application
        throw new Error('Failed to parse actionCode');
      }
    }

    return {
      ...rest,
      ...(startDate && { startDate: new Date(startDate) }),
      ...(endDate && { endDate: new Date(endDate) }),
      ...(createdAt && { createdAt: new Date(createdAt) }),
      ...(updatedAt && { updatedAt: new Date(updatedAt) }),
      ...(actionCode && { actionCode: parsedActionCode }),
    };
  }
}
