import axios from 'axios';
import type { ActionResponseTypes } from 'src/types/GlobalTypes';
import { apiConfig } from '@/config/api.config';
import { useCallApi } from '@/hooks';

interface SaveLogsParams {
  module: string;
  description: string;
  action: string;
}

const API_URL = apiConfig.service_dashboard;

const getCurrentTimeJakarta = () => {
  const jakartaTime = new Date().toLocaleString('id-ID', {
    timeZone: 'Asia/Jakarta',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });

  const [date, time] = jakartaTime.split(' ');
  const [day, month, year] = date.split('/');

  return `${year}-${month}-${day} ${time}`;
};

export async function doSaveLogActivity(payload: SaveLogsParams): Promise<ActionResponseTypes> {
  try {
    const token = JSON.parse(localStorage.getItem(`${import.meta.env.VITE_APP_NAME}-auth-v${import.meta.env.VITE_APP_VERSION}`) || '{}');

    const dtParams = {
      ...payload,
      id_user: token.id,
      refresh_token: token.refresh_token,
      url: window.location.href,
      data_body: getCurrentTimeJakarta(),
    };

    const response = await axios.post(`${API_URL}/user_activity/create`, dtParams);

    if (response.status !== 200 || !response.data.status) {
      throw new Error(response.data.message ?? 'Failed to save log');
    }

    console.log('Success Create logs with params =>', dtParams);

    return { status: true, message: 'Success logs users' };
  } catch (error: any) {
    console.error('Error saving log:', error.message);
    return { status: false, message: error.message };
  }
}
