import axios from 'axios';
import { v4 as uuidv4 } from 'uuid';

//live 
//const WISE_API_URL = "https://api.transferwise.com"; 
//const WISE_API_KEY = "9a392ee6-13e3-4e94-83d5-19a41428726d";

//Sendbox 
const WISE_API_URL = "https://api.sandbox.transferwise.tech";
const WISE_API_KEY = "925e7848-b09b-462a-9570-569b4ef71cdc";

const wiseClient = axios.create({
  baseURL: WISE_API_URL,
  headers: {
    Authorization: `Bearer ${WISE_API_KEY}`,
    'Content-Type': 'application/json',
  },
});

// Step 1: Create or Get Recipient Account
export async function createOrGetRecipientAccount(accountData: any) {
  try {
    // Check if recipient account already exists
    const existingAccounts = await wiseClient.get(`/v1/accounts`, {
      params: { currency: accountData.currency },
    });

    //console.log("existingAccounts", existingAccounts.data);

    const existingAccount = existingAccounts.data.find((account: any) => {
      return account.details.accountNumber === accountData.details.accountNumber;
    });

    if (existingAccount) {
      console.log('Recipient account exists:', existingAccount.id);
      return existingAccount.id;
    } else {
      // Create new recipient account
      const recipientAccountResponse = await wiseClient.post('/v1/accounts', accountData);
      console.log('New recipient account created:', recipientAccountResponse.data.id);
      return recipientAccountResponse.data.id;
    }
  } catch (error: any) {
    console.error('Error:', error.response?.data?.errors);
    console.error('Error creating or getting recipient account:', error.response?.data || error.message);
    throw new Error('Failed to create or get recipient account');
  }
}

// Step 2: Create a Quote for the Transfer
export async function createQuote(transferData: any) {
  try {
    const quoteResponse = await wiseClient.post('/v1/quotes', {
      source: transferData.sourceCurrency,    // Valid source currency code (e.g., 'USD')
      target: transferData.targetCurrency,    // Valid target currency code (e.g., 'EUR')
      sourceAmount: transferData.sourceAmount, // Amount to transfer
      rateType: 'FIXED',  // Specify the rate type ('FIXED' is typical for Wise)
    });
    console.log('Quote created:', quoteResponse.data.id);
    return quoteResponse.data;
  } catch (error: any) {
    console.error('Error creating quote:', error.response?.data || error.message);
    throw new Error('Failed to create quote');
  }
}

// Step 3: Create the Money Transfer
export async function createTransfer(quoteId: string, recipientAccountId: string) {
  const customerTransactionId = uuidv4();
  try {
    const transferResponse = await wiseClient.post('/v1/transfers', {
      targetAccount: recipientAccountId, // The recipient account ID
      quote: quoteId, // Quote ID from the quote creation
      customerTransactionId: customerTransactionId, // Unique transaction ID using timestamp
      details: {
        reference: 'Payment', // Optional reference for the transfer
      },
    });
    console.log('Transfer created:', transferResponse.data.id);
    return transferResponse.data;
  } catch (error:any) {
    console.error('Error creating transfer:', error.response?.data || error.message);
    throw new Error('Failed to create transfer');
  }
}

// Step 4: Fund the Transfer
export async function fundTransfer(profileId: string, transferId: string) {
  try {
    // Make the API call to fund the transfer
    const fundResponse = await wiseClient.post(`/v3/profiles/${profileId}/transfers/${transferId}/payments`, {
      type: 'BALANCE', // Specify the funding type, e.g., 'BALANCE', 'ACH', 'CARD'
    });

    console.log('Transfer funded successfully:', fundResponse.data);
    return fundResponse.data;
  } catch (error: any) {
    console.error('Error funding transfer:', error.response?.data || error.message);
    throw new Error('Failed to fund transfer');
  }
}

// Function to retrieve the profile ID
export async function getProfileId() {
  try {
    // Make the API call to retrieve all profiles
    const response = await wiseClient.get('/v1/profiles');
    const profiles = response.data;
    // Assuming you're looking for a personal profile; otherwise, adjust the filtering logic
    const personalProfile = profiles.find((profile: any) => profile.type === 'personal');

    if (!personalProfile) {
      throw new Error('No personal profile found');
    } 
    //console.log("Profile data - ", personalProfile);    
    console.log("Profile id - ", personalProfile.id);    
    return personalProfile.id; // Return the personal profile ID
  } catch (error: any) {
    console.error('Error retrieving profile:', error.response?.data || error.message);
    throw new Error('Failed to retrieve profile ID');
  }
}

// check transferId is vaild
export async function getTransferDetails(transferId: string) {
  try {
    const transferDetails = await wiseClient.get(`/v1/transfers/${transferId}`); 
    return transferDetails.data;
  } catch (error: any) {
    console.error('Error retrieving transfer details:', error.response?.data || error.message);
    throw new Error('Failed to retrieve transfer details');
  }
}

// recipient account, check its details
export async function getRecipientAccount(recipientId: string) {
  try {
    const response = await wiseClient.get(`/v2/accounts/${recipientId}`); 
    return response.data
  } catch (error: any) {
    console.error('Error retrieving recipient account:', error.response?.data || error.message);
  }
}

// all accounts
export async function getAllRecipientAccounts() {
  try {
    const response = await wiseClient.get('/v1/accounts');
    console.log('Recipient accounts:', response.data);
    return response.data;
  } catch (error: any) {
    console.error('Error retrieving recipient accounts:', error.response?.data || error.message);
    throw new Error('Failed to get recipient accounts');
  }
}
 