const { asyncHandler } = require("../middleware/errorHandler");
const axios = require('axios');
const { Plan, Asset, Network, CoinNetwork, NetworkAddress, sequelize, MarketPair, SymbolStats } = require("../models");
const country = require("../config/country")
const { fiat_currency } = require("../config/currency")
const ApiResponse = require("../utils/apiResponse");
const { transporter, generateRandomString, sendEmail, notifyUser } = require("../utils/helpers");
const { makeMnemonic, seedFromMnemonic, generateBTC, generateEVM, generateTRON, deriveAll } = require("../utils/wallet");
const conversionService = require("../services/conversionService");
const tradingPairService = require("../services/tradingPairService");
const logger = require("../utils/logger");
const { walletGenerator, createwallet } = require("../utils/walletGenerator");
const userService = require("../services/admin/userService");
const { updateMarketRates } = require("../services/updateMarket");

exports.getJob = asyncHandler(async (req, res) => {
  const n = await updateMarketRates()
  ApiResponse.success(res, { data: n }, 'broadcast Sent');
})

exports.getPlans = asyncHandler(async (req, res) => {
  const getplans = await Plan.findAll({
    where: { status: true }
  })

  const plans = getplans.map(p => ({
    id: p.id,
    name: p.name,
    badge: p.tagline,
    description: p.description,
    price: p.price,
    maxPrice: p.maxPrice,
    duration: `${p.duration} ${p.duration > 1 ? p.durationType + 's' : p.durationType}`,
    highlight: p.highlight,
    features: p.features,
    limits: p.limits,
    config: p.config
  }))

  ApiResponse.success(res, plans);
});

exports.getAssets= asyncHandler(async (req, res) => {
  const getpairs = await MarketPair.findAll({
    where: { type: 'spot' },
    include: [{model: SymbolStats , as: 'rate'}]
  })

  const pairs = getpairs.map(p => ({
    id: p.id,
    symbol: p.symbol,
    price: p.rate?.current_price || null,
  }))

  ApiResponse.success(res, pairs);
});

exports.getBinance = asyncHandler(async (req, res) => {
  //const result = await conversionService.fetchBinancePrice('BTC' , 'USDT')
  //const geckp = await conversionService.fetchCoinGeckoPrice('BTC', 'USD')
  //const usd = await conversionService.fetchForexRate('USD' , 'GBP')
  //const stock = await conversionService.fetchStockTwelvePrice('AMZN')
  const s = await conversionService.fetchCMCData('BTC')
  if (res.app.locals.broadcastCall) {
    res.app.locals.broadcastCall({ type: 'data', message: "updated the server", time: new Date() })
  }
  ApiResponse.success(res, { s }, 'broadcast Sent');
})




exports.getLogin = asyncHandler(async (req, res) => {
  let email = "huilong1609@gmail.com"
  const code = 123456
  let ress = null;
  try {
    axios.post(
      'https://invsta.website/sendemail.php',
      {
        email,
        code: code
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ashieiuejidjkdlk_woiowwiwk.sjjs2729829kAJHjahnm'
        },

      }
    ).then(() => logger.info(`OTP email sent: ${email}`))
      .catch((err) => logger.info({ err }, `OTP email failed: ${email}`))

    ApiResponse.success(res, { resp: ress?.data, currency: fiat_currency, country });
  } catch (err) {
    ApiResponse.error(res, 'error occured', 500, err.message)
  }


  /* fetch('https://invsta.website/sendemail.php' , {
        method: 'POST',
        headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer authorization key'
    },
    body: JSON.stringify({
        email,
        code: otp.code
    })
    }).then(() => logger.info(`OTP email sent: ${email}`))
      .catch((err) => logger.info({ err }, `OTP email failed: ${email}`)); */

});

exports.updateRates = asyncHandler(async (req, res) => {
  const stock = await conversionService.getCryptoPrices();

  ApiResponse.success(res, { stock }, 'Rate updated');
});

exports.cronJob = asyncHandler(async (req, res) => {
  const stock = await conversionService.updateCron();
  //const binance = await conversionService.fetchBinancePrice()
  ApiResponse.success(res,  stock , 'Rate updated');
});


exports.testPublic = asyncHandler(async (req, res) => {
  /* const notify = {
    title: "Test Notification",
    message: "This is a test notification",
    type: "system",
    channels: {
      inApp: true,
      email: true,
      push: false,
      sms: false
    },
    priority: "medium",
  }
  const stock = await userService.notifyUser(24, notify , 1); */
  const spot = await Asset.findAll({
    where: { type: 'stock' }
  })
  ApiResponse.success(res,  { spot: spot.map(s => ({ symbol: s.symbol , pairId: s.id})) } , 'notified');
});

exports.generateWallet = asyncHandler(async (req, res) => {

  const wallet = await deriveAll({
    mnemonicStrength: 128,
    passphrase: "",        // optional BIP39 passphrase
    testnetBTC: false,
    includeSecrets: true, // SAFE DEFAULT
  });
  ApiResponse.success(res, { wallet });
});


exports.sendEmail = asyncHandler(async (req, res) => {

  const info = await transporter.sendMail({
    from: '"My App" <no-reply@elitetrustvault.com>',
    to: 'ejirojames2000@gmail.com',
    subject: 'Welcome 🎉',
    text: 'Welcome to My App',
    html: '<h2>Welcome to My App</h2>',
  });
  ApiResponse.success(res, info.messageId, 'message sent');
})