const { asyncHandler } = require('../middleware/errorHandler');
const fundService = require('../services/fundService');
const ApiResponse = require('../utils/apiResponse');
const { buildPublicFileUrl } = require('../utils/fileUrl');
const path = require('path')

exports.getDeposit = asyncHandler(async(req , res) => {
    const deposit = await fundService.getDeposit();
    ApiResponse.success(res , deposit)
})

exports.payDeposit = asyncHandler(async(req , res) => {
    const {id} = req.params
    const deposit = await fundService.payDeposit(req.user.id, id);
    ApiResponse.success(res , deposit)
})
exports.uploadDeposit = asyncHandler(async (req, res) => {
  if (!req.file) {
    throw new BadRequestError('File is required');
  }

  const relativeFilePath = path.join('uploads', 'deposits', req.file.filename);
  const fileUrl = buildPublicFileUrl(req, relativeFilePath);

  const data = await fundService.uploadDeposit(req.user.id, {
    transactionId: req.body.transactionId,
    fileName: req.file.filename,
    fileUrl
  });

  ApiResponse.success(res, {
    message: 'Document uploaded successfully',
    data: {
      ...data,
      file: {
        url: fileUrl,
        fileName: req.file.originalname,
      },
    },
  });
});

exports.startDeposit = asyncHandler(async(req , res) => {
    const deposit = await fundService.startDeposit(req.user.id, req.user.currency, req.body);
    ApiResponse.success(res , deposit)
})

exports.cancelDeposit = asyncHandler(async(req , res) => {
    const {id} =  req.params;
    if(!req.body?.transactionId){
       throw new BadRequestError('Provide a  transactionId');
    }
     if (id !== req.body.transactionId) {
    throw new BadRequestError('Invalid transactionId');
  }
  
  
    const deposit = await fundService.cancelDeposit(req.user.id , req.body.transactionId);
    ApiResponse.success(res , deposit)
})

exports.getWithdrawal = asyncHandler(async(req , res) => {
    const withdrawal = await fundService.getWithdrawal(req.user.id);
    ApiResponse.success(res , withdrawal)
})

exports.makeWithdrawal = asyncHandler(async(req , res) => {
    const withdrawal = await fundService.makeWithdrawal();
    ApiResponse.success(res , withdrawal)
})

exports.requestWithdrawal =  asyncHandler(async(req , res) => {
    const withdrawal = await fundService.confirmWithdrawal(req.user.id, req.user.currency, req.body);
    ApiResponse.success(res , withdrawal)
})

exports.getHistory = asyncHandler(async(req , res) => {
    const history = await fundService.getHistory(req.user.id);
    ApiResponse.success(res , history)
})