import { Request, Response } from "express";
import Stripe from "stripe";
import yenv from "yenv";
import { Transaction } from "../../database/transaction/transaction";
import { Notification } from "../../database/notification/notification";
import { messages } from "../../utills/common";
const env = yenv("env.yaml", { env: "development" });
const stripe = new Stripe(env.STRIPE_SECRET_KEY as string, { apiVersion: "2024-04-10" });
export const depositByUser = async (req: Request, res: Response) => {
  const { amount} = req.body;
  const context = (req as any).user;
  console.log(context);
  
  try {
    const session = await stripe.checkout.sessions.create({
      payment_method_types: ['card'],
      line_items: [{
        price_data: {
          currency: 'usd',
          product_data: {
            name: 'Your Product Name',
          },
          unit_amount: convertDollarsToCents(amount),
        },
        quantity: 1,
      }],
      mode: 'payment',
      success_url: 'https://yourdomain.com/success?session_id={CHECKOUT_SESSION_ID}',
      cancel_url: 'https://yourdomain.com/cancel',
    });
    await Transaction.create({userId:context.id,depositAmount:amount,totalInvestedAmount: amount}).save();
    await Notification.create({userId:context.id,msg: messages.notificationDepositMessage,}).save();
    res.json({ url: session.url });
  } catch (error:any) {
    res.status(500).json({ error: error.message });
  }
};

function convertDollarsToCents(input:any) {
  const dollars = parseFloat(input);
  const cents = Math.round(dollars * 100);
  return cents;
}


export const depositAmountByUser = async (req: Request, res: Response) => {
  const { amount} = req.body;
  const context = (req as any).user;

  try {
    const customer = await stripe.customers.create();
    const ephemeralKey = await stripe.ephemeralKeys.create(
      {customer: customer.id},
      {apiVersion: '2023-08-16'}
    );
    const paymentIntent = await stripe.paymentIntents.create({
      amount: convertDollarsToCents(amount),
      currency: 'usd',
      customer: customer.id,
      automatic_payment_methods: {
        enabled: true,
      },
    });
      await Transaction.create({userId:context.id,depositAmount:amount,totalInvestedAmount: amount}).save();
    await Notification.create({userId:context.id,msg: messages.notificationDepositMessage,}).save();
    res.json({
      paymentIntent: paymentIntent.client_secret,
      ephemeralKey: ephemeralKey.secret,
      customer: customer.id,
      publishableKey: env.STRIPE_PUBLISHABLE_KEY
    });
  } catch (error:any) {
    res.status(500).json({ error: error.message });
  }
};