import {GET, POST, PUT} from './';
import {
  CreateSavingsParams,
  UpdateSavingsParams,
  FundSavingsParams,
} from './types';
import {InterestBreakdownType} from '../utils/types';
import {API_GATEWAY_BASE_URL} from '../env.json';

export const getAllSavingsCategories = async (apiKey: string) => {
  try {
    const response = await GET({
      requestUrl: 'SavingsCategory/GetAllSavingsCategories',
      apiKey,
    });
    return response;
  } catch (error: any) {
    return error;
  }
};

export const getAllPlans = async (apiKey: string) => {
  try {
    const response = await GET({
      requestUrl: 'Plans/GetAllPlans',
      apiKey,
    });
    return response;
  } catch (error: any) {
    return error;
  }
};

export const createPlan = async (apiKey: string, planName: string) => {
  try {
    const response = await POST({
      requestUrl: 'Plans/AddPlans',
      apiKey,
      requestData: {name: planName},
    });
    return response;
  } catch (error: any) {
    return error;
  }
};

export const createSavingsAccount = async (
  apiKey: string,
  params: CreateSavingsParams,
) => {
  try {
    const response = await POST({
      requestUrl: 'Savings/CreateSavingsAccount',
      apiKey,
      requestData: params,
    });
    return response;
  } catch (error: any) {
    return error;
  }
};

export const updateSavingsAccount = async (
  apiKey: string,
  params: UpdateSavingsParams,
) => {
  try {
    const response = await PUT({
      requestUrl: 'Savings/UpdateSavingsAccount',
      apiKey,
      requestData: params,
    });
    return response;
  } catch (error: any) {
    return error;
  }
};

export const getSavingsListByCustomerId = async (apiKey: string) => {
  try {
    const response = await GET({
      requestUrl: 'Savings/GetSavingsListByCustomerId',
      apiKey,
    });
    return response;
  } catch (error: any) {
    return error;
  }
};

export const getSavingsDetailsBySavingsId = async (
  apiKey: string,
  savingsId: string,
) => {
  try {
    const response = await GET({
      requestUrl: `Savings/GetSavingsDetailsBySavingsId/${savingsId}`,
      apiKey,
    });
    return response;
  } catch (error: any) {
    return error;
  }
};

export const getTotalAccountTransactionsByCustomerId = async (
  apiKey: string,
) => {
  try {
    const response = await GET({
      requestUrl: 'SavingsTransaction/GetTotalAccountTransactionsByCustomerId',
      apiKey,
    });
    return response;
  } catch (error: any) {
    return error;
  }
};

export const getSavingsTransactionsList = async (
  apiKey: string,
  params: {
    savingsId: string;
    recordsPerPage?: number;
    transactionType?: string;
    startDate?: string;
    endDate?: string;
    search?: string;
    narration?: string;
    status?: string;
    nextPageToken?: string;
  },
) => {
  try {
    const queryParams = new URLSearchParams();
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null) {
        queryParams.append(key, value.toString());
      }
    });

    const response = await GET({
      requestUrl: `SavingsTransaction/TransactionsList?${queryParams.toString()}`,
      apiKey,
    });
    return response;
  } catch (error: any) {
    return error;
  }
};

export const getSavingsTransactionHistory = async (
  apiKey: string,
  params: {
    recordsPerPage?: number;
    transactionType?: string;
    startDate?: string;
    endDate?: string;
    nextPageToken?: string;
  },
) => {
  try {
    const queryParams = new URLSearchParams();
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null) {
        queryParams.append(key, value.toString());
      }
    });

    const response = await GET({
      requestUrl: `SavingsTransaction/History?${queryParams.toString()}`,
      apiKey,
    });
    return response;
  } catch (error: any) {
    return {
      error: true,
      message: 'An error occurred while getting interest breakdown',
      data: null,
    };
  }
};

export const getWalletBalance = async (apiKey: string) => {
  try {
    const requestHeaders = {
      authorization: `Bearer ${apiKey}`,
      'content-type': 'application/json',
    };

    const response = await fetch(`${API_GATEWAY_BASE_URL}/wallet/balance`, {
      method: 'GET',
      headers: requestHeaders,
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const responseData = await response.json();

    if (responseData.error === true) {
      return {
        error:
          responseData.message ??
          'An error occurred while fetching wallet balance',
      };
    }

    return responseData;
  } catch (error: any) {
    return {
      error: error.message ?? 'Failed to fetch wallet balance',
    };
  }
};

export const fundSavingsAccount = async (
  apiKey: string,
  params: FundSavingsParams,
) => {
  try {
    const response = await POST({
      requestUrl: 'SavingsTransaction/FundSavingsAccountManually',
      requestData: params,
      apiKey,
    });
    return response;
  } catch (error: any) {
    return error;
  }
};

export const withdrawFromSavingsAccount = async (
  apiKey: string,
  params: {savingsId: string; amount: number},
) => {
  try {
    const response = await POST({
      requestUrl: 'SavingsTransaction/WithdrawFromSavingsAccount',
      requestData: params,
      apiKey,
    });
    return response;
  } catch (error: any) {
    return error;
  }
};

export const getInterestBreakdownBySavingsId = async (
  savingsId: string,
  apiKey: string,
) => {
  try {
    const response = await GET({
      requestUrl: `SavingsTransaction/GetInterestBreakdownBySavingsId/${savingsId}`,
      apiKey,
    });

    return {
      error: false,
      message: 'Interest breakdown retrieved successfully',
      data: response as InterestBreakdownType[],
    };
  } catch (error) {
    console.error('Error getting interest breakdown:', error);
    return {
      error: true,
      message: 'An error occurred while getting interest breakdown',
      data: null,
    };
  }
};

export const getLockedSavingsInterestRateTiers = async (apiKey: string) => {
  try {
    const response = await GET({
      requestUrl: 'SavingsCategory/GetLockedSavingsInterestRateTiers',
      apiKey,
    });
    return response;
  } catch (error: any) {
    return error;
  }
};
