Can you add loging to this function, refactor it if needed, and solve problem if needed, and then tell me what you did ?

import { SQS } from "aws-sdk";
import { queryFrApi } from '../../utils/frApi';
import { sendToMasterData } from '../../utils/masterApi'
import \* as type from '../../utils/types'

const sqs = new SQS();

export const handler = async (event: any) => {

 var params = {
 QueueUrl: 'https://sqs.eu-west-2.amazonaws.com/806798940075/product-headers-qeue-jm',
 VisibilityTimeout: 10,
 WaitTimeSeconds: 10
 };

 let receiptHandle = '';
 let product: type.Product = {
 ITMDES1: '',
 IMG: '',
 ITMREF: '',
 $uuid: ''
 };
 sqs.receiveMessage(params, function(err, data) {
 if (err) {
 throw new Error('Failed to poll message');
 } else if (data) {
 console.log('I AM HERE')
 console.log('LENGTH' + Object.keys(data).length)
 receiptHandle = data.Messages![0].ReceiptHandle!;
 product = JSON.parse(data.Messages![0].Body!)
 } 
 });

 const detailsAPI = await queryFrApi(
 `https://x3.etcfr.f12cloud.pt:444/api1/x3/erp/X3V12\_ETCFR/YCCPRODUCT('${product['ITMREF']}')?representation=YCCPRODUCT.$details`,
 );

 // fetch stocks
 const stockAPICall = await queryFrApi(
 `https://x3.etcfr.f12cloud.pt:444/api1/x3/erp/X3V12\_ETCFR/ITMMVT?representation=YCCSTOCK.$query&orderBy=ITMREF&where=(ITMREF) eq '${product['ITMREF']}'&count=100`,
 );
 const stockAPI: type.stockResource[] = stockAPICall['$resources'];

 // fetch sells
 const sellsAPICall = await queryFrApi(
 `https://x3.etcfr.f12cloud.pt:444/api1/x3/erp/X3V12\_ETCFR/YCCPPRICLIST?representation=YCCPPRICLIST.$query&where=(PLICRI2) eq '${product['ITMREF']}'`,
 );
 const sellsAPI: type.sellResource[] = sellsAPICall['$resources'];

 // add the image to the products that have {}
 if (product.IMG != null) {
 typeof product.IMG === 'object' && Object.keys(product.IMG).length === 0
 ? (product.IMG = await queryFrApi(
 `https://x3.etcfr.f12cloud.pt:444/api1/x3/erp/X3V12\_ETCFR/BDOC('C\_YCCPRODUCT~%C2%A8~IMG~%C2%A8~ITM~%C2%A8~${product['ITMREF']}~%C2%A8~')`,
 ))
 : null;
 }

 const branchName = detailsAPI.$actxFolder

 const masterBranch = {
 branchName: branchName,
 language: detailsAPI.$actxLan
 }

 const masterProduct = {
 productName: product.ITMREF,
 imageUrl: product.IMG,
 description: product.ITMDES1,
 branchName: branchName,
 manufacturerPartNumber: product.$uuid,
 categories: {
 main: detailsAPI.ITMCZTSICOD?.[0]?.ZTSICOD,
 sub: detailsAPI.ITMCZTSICOD?.[1]?.ZTSICOD,
 leaf: detailsAPI.ITMCZTSICOD?.[2]?.ZTSICOD,
 }
 }

 const masterManufacturer = {
 name: 'anonymous'
 }

 const masterSells = [];
 for (const sell of sellsAPI) {
 const filterSell: type.ObjectSell = {
 price: sell.PRI,
 partNumber: sell.PLICRI2,
 productName: product.ITMREF,
 manufacturerName: 'anonymous',
 branchName: branchName
 };
 masterSells.push(filterSell); 
 }

 const masterStocks = [];
 const masterWarehouse = [];
 for (const stock of stockAPI) {
 const filterStock: type.ObjectStock = {
 address: stock.STOFCY,
 quantity: stock.SALSTO,
 productName: product.ITMREF,
 branchName: branchName
 };
 masterStocks.push(filterStock);

 const filterWarehouse = {
 address: stock.STOFCY,
 branchName: branchName
 }
 masterWarehouse.push(filterWarehouse)
 }

 try {
 const result = await sendToMasterData(masterBranch, '/addBranch');
 
 if (result === 200) {
 const results1 = await Promise.all([
 sendToMasterData(masterProduct, '/addProduct'),
 sendToMasterData(masterManufacturer, '/addManufacturer'),
 Promise.all(masterWarehouse.map(warehouse => sendToMasterData(warehouse, '/addWarehouse')))
 ]);

 if ( results1.every(value => value === 200) ) { 
 const results2 = await Promise.all([
 Promise.all(masterStocks.map(stock => sendToMasterData(stock, '/addStock'))),
 Promise.all(masterSells.map(sell => sendToMasterData(sell, '/addSell')))
 ]);
 } else {
 if (results1[0] !== 200){
 return {
 statusCode: 200,
 body: 'An error occurred while adding product',
 };
 } else if (results1[1] !== 200) {
 return {
 statusCode: 200,
 body: 'An error occurred while adding manufacturer',
 };
 } else {
 return {
 statusCode: 200,
 body: 'An error occurred while adding warehouse',
 };
 }
 }
 } else {
 return {
 statusCode: 200,
 body: 'An error occurred while adding a branch',
 };
 }
 
 } catch (error) {
 console.error('An error occurred:', error);
 return {
 statusCode: 200,
 body: 'An error occurred',
 };
 }

 const paramsDelete = {
 QueueUrl: 'https://sqs.eu-west-2.amazonaws.com/806798940075/product-headers-qeue-jm',
 ReceiptHandle: receiptHandle,
 };
 
 sqs.deleteMessage(paramsDelete, (err, data) => {
 if (err) {
 console.log('Error deleting message from queue:', err);
 } else {
 console.log('Message deleted from queue:', data);
 }
 });
 
 return { message: 'ok' }
}
이 함수에 로깅을 추가하고, 필요한 경우 리팩터링하고, 필요한 경우 문제를 해결 한 다음 무엇을했는지 알려주시겠습니까?"aws-sdk"에서 { SQS }를 가져옵니다;'../../utils/frApi'에서 { queryFrApi }를 임포트합니다;'../../utils/masterApi'에서 { sendToMasterData }를 임포트합니다.'../../utils/types'에서 \*를 유형으로 임포트합니다.const sqs = new SQS();export const handler = async (event: any) => { var params = { QueueUrl: 'https://sqs.eu-west-2.amazonaws.com/806798940075/product-headers-qeue-jm', VisibilityTimeout: 10, WaitTimeSeconds: 10 }; let receiptHandle = ''; let product: type.Product = { ITMDES1: '', IMG: '', ITMREF: '', uuid: '' }; sqs.receiveMessage(params, function(err, data) { if (err) { 새로운 오류('메시지 폴링에 실패했습니다')를 던집니다; } else if (data) { console.log('I AM HERE') console.log('LENGTH' + Object.keys(data).length) receiptHandle = data.Messages![0].ReceiptHandle! product = JSON.parse(data.Messages![0].Body!) }  }); const detailsAPI = await queryFrApi( `https://x3.etcfr.f12cloud.pt:444/api1/x3/erp/X3V12\_ETCFR/YCCPRODUCT('${product['ITMREF']}')?representation=YCCPRODUCT.$details`, ); // 주식 불러오기 const stockAPICall = await queryFrApi( `https://x3.etcfr.f12cloud.pt:444/api1/x3/erp/X3V12\_ETCFR/ITMMVT?representation=YCCSTOCK.$query&orderBy=ITMREF&where=(ITMREF) eq '${product['ITMREF']}'&count=100`, ); const stockAPI: type.stockResource[] = stockAPICall['$resources']; // sells 불러오기 const sellsAPICall = await queryFrApi( `https://x3.etcfr.f12cloud.pt:444/api1/x3/erp/X3V12\_ETCFR/YCCPPRICLIST?representation=YCCPPRICLIST.$query&where=(PLICRI2) eq '${product['ITMREF']}'`, ); const sellsAPI: type.sellResource[] = sellsAPICall['$resources']; // {}가 있는 제품에 이미지 추가 if (product.IMG != null) { typeof product.IMG === 'object' && Object.keys(product.IMG).length === 0 ? (product.IMG = await queryFrApi( `https://x3.etcfr.f12cloud.pt:444/api1/x3/erp/X3V12\_ETCFR/BDOC('C\_YCCPRODUCT~%C2%A8~IMG~%C2%A8~ITM~%C2%A8~${product['ITMREF']}~%C2%A8~')`, )) : null; } const branchName = detailsAPI.$actxFolder const masterBranch = { branchName: 지점명, 언어: detailsAPI.$actxLan } const masterProduct = { 제품명: product.ITMREF, imageUrl: product.IMG, 설명: product.ITMDES1, branchName: 지점명, 제조사부품번호: product.$uuid, categories: { main: detailsAPI.ITMCZTSICOD?..[0]?.ZTSICOD, sub: detailsAPI.ITMCZTSICOD?.[1]?.ZTSICOD, leaf: detailsAPI.ITMCZTSICOD?..[2]?.ZTSICOD, } } const masterManufacturer = { name: '익명' } const masterSells = []; for (sellsAPI의 const sell) { const filterSell: type.ObjectSell = { price: sell.PRI, partNumber: sell.PLICRI2, productName: product.ITMREF, 제조사명 '익명', branchName: 지점명 }; masterSells.push(filterSell);  } const masterStocks = []; const masterWarehouse = []; for (stockAPI의 const stock) { const filterStock: type.ObjectStock = { 주소: stock.STOFCY, 수량: stock.SALSTO, productName: product.ITMREF, 지점명: 지점명 }; masterStocks.push(filterStock); const filterWarehouse = { 주소: stock.STOFCY, 지점명: 지점명 } masterWarehouse.push(filterWarehouse) } try { const result = await sendToMasterData(masterBranch, '/addBranch');  if (result === 200) { const results1 = await Promise.all([[ sendToMasterData(masterProduct, '/addProduct'), sendToMasterData(masterManufacturer, '/addManufacturer'), Promise.all(masterWarehouse.map(warehouse => sendToMasterData(warehouse, '/addWarehouse')))) ]); if ( results1.every(value => value === 200) ) {  const results2 = await Promise.all([[ Promise.all(masterStocks.map(stock => sendToMasterData(stock, '/addStock'))), Promise.all(masterSells.map(sell => sendToMasterData(sell, '/addSell'))) ]); } else { if (results1[0] !== 200){ return { statusCode: 200, body: '상품을 추가하는 동안 오류가 발생했습니다', }; } else if (results1[1] !== 200) { return { statusCode: 200, body: '제조업체를 추가하는 동안 오류가 발생했습니다', }; } else { 반환 { statusCode: 200, body: '웨어하우스를 추가하는 동안 오류가 발생했습니다', }; } } } else { 반환 { statusCode: 200, body: '브랜치를 추가하는 동안 오류가 발생했습니다', }; }  } catch (error) { console.error('오류가 발생했습니다:', error); 반환 { statusCode: 200, body: '오류가 발생했습니다', }; } const paramsDelete = { QueueUrl: 'https://sqs.eu-west-2.amazonaws.com/806798940075/product-headers-qeue-jm', ReceiptHandle: 수신 핸들, };  sqs.deleteMessage(paramsDelete, (err, data) => { if (err) { console.log('대기열에서 메시지를 삭제하는 중 오류 발생:', err); } else { console.log('메시지가 큐에서 삭제되었습니다:', data); } });  반환 { message: 'ok' }}