const asyncHandler = require("express-async-handler");
const fetch = require('node-fetch');
const { LotDb } = require("../services/lotDb");
const lotDb = new LotDb();
const { SaleDb } = require("../services/saleDb");
const saleDb = new SaleDb();

const ApiURL = "http://host.docker.internal:3020/api";

// scrapping
exports.getInfos = asyncHandler(async (req, res, next) => {
	  let url = req.params.url

    url = encodeURIComponent(url);

    fetch(ApiURL+'/lot/getInfos/'+url)
      .then(response => response.json())
      .then(data => {
        res.json(data); 
      })
      .catch(error => {
        console.error(error);
        res.json({error: error}); 
        
    });
});

exports.getPictures = asyncHandler(async (req, res, next) => {
  let url = req.params.url

  url = encodeURIComponent(url);

  fetch(ApiURL+'/lot/getPictures/'+url)
    .then(response => response.json())
    .then(data => {
      res.json(data); 
    })
    .catch(error => {
      console.error(error);
      res.json({error: error}); 
  });
});

exports.getLotsBySale = asyncHandler(async (req, res, next) => {
  let id = req.params.id
  
  const Sale = await saleDb.get(id);
  if(!Sale){
    console.error("Sale not found");
    return res.status(404).send({error: "Sale not found"});
  }
  
  Lots = await lotDb.getBySaleId(Sale._id.toString(),Sale.platform);
  res.json(Lots);  

});

// Follow Sale
exports.NextItem = asyncHandler(async (req, res, next) => {
  try{
    
    
    Sale = await saleDb.getByIDPlatform(req.body.idSalePlatform, req.body.platform);
    if(!Sale){
      console.error("Sale not found");
      return res.status(404).send({error: "Sale not found"});
    }      
    
    let Lot = await lotDb.getByIDPlatform(req.body.idPlatform, req.body.platform);
    if(Lot == null){
      console.log("Creating new Lot");      
      
      Lot = {
        idPlatform: String(req.body.idPlatform),
        platform: req.body.platform,
        timestamp: req.body.timestamp,
        lotNumber: String(req.body.lotNumber),
        title: req.body.title,
        description: req.body.description,
        EstimateLow: req.body.EstimateLow,
        EstimateHigh: req.body.EstimateHigh,
        RawData: req.body.RawData,
        sale_id: Sale._id,        
      }

      await lotDb.post(Lot);

    }else{
      console.log("Updating Lot");  
            
      Lot.timestamp = req.body.timestamp;
      Lot.lotNumber = String(req.body.lotNumber);
      Lot.title = req.body.title;
      Lot.description = req.body.description;
      Lot.EstimateLow = req.body.EstimateLow;
      Lot.EstimateHigh = req.body.EstimateHigh;
      Lot.RawData = req.body.RawData;
            
      await lotDb.put(Lot._id, Lot);      
    }
    
    res.status(204).send({message: "Lot updated"});
  }catch(err){
      console.log(err);
      return res.status(500).send({error: err});
  }
});

exports.Bid = asyncHandler(async (req, res, next) => {
  try{
    let Lot = await lotDb.getByIDPlatform(req.body.idPlatform, req.body.platform);
    
    if(Lot){
      console.log("Update Lot Bid");      
      
      BidInfo = {        
        timestamp: req.body.timestamp,
        amount: req.body.amount,
        auctioned_type: req.body.auctioned_type,       
      }
      // If Lot.BidInfo doesn't exist, initialize it as an empty array
      if (!Lot.Bids) {
        Lot.Bids = [];
      }

      // Add BidInfo to the array
      Lot.Bids.push(BidInfo);

      await lotDb.put(Lot._id, Lot);
    }else{
      console.error("Lot not found");
      return res.status(404).send({error: "Lot not found"});
    }
    
    res.status(204).send({message: "Lot updated"});
  }catch(err){
      console.log(err);
      return res.status(500).send({error: err});
  }
});

exports.AuctionedItem = asyncHandler(async (req, res, next) => {
  try{
    
    let Lot = await lotDb.getByIDPlatform(req.body.idPlatform, req.body.platform);
    
    if(Lot){
      console.log("Update Lot AuctionedItem");      
      
      Lot.auctioned = {           
        timestamp: req.body.timestamp,
        amount: req.body.amount,
        auctioned_type: req.body.auctioned_type,
        sold: req.body.sold,       
      }
      
      await lotDb.put(Lot._id, Lot);

      //update stats
      await saleDb.processStats(Lot.sale_id);

    }else{
      console.error("Lot not found");
      return res.status(404).send({error: "Lot not found"});
    }
    
    res.status(204).send({message: "Lot updated"});
  }catch(err){
      console.log(err);
      return res.status(500).send({error: err});
  }
});

// DB
exports.get = asyncHandler(async (req, res, next) => {

  try{
      const id = req.params.id;      
      let result = await lotDb.get(id);      
      res.status(200).send(result);
  }catch(err){
      console.log(err);
      return res.status(500).send({error: err});
  }
  
});

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

  try{
      // check if double
      let Lot = await lotDb.getByIDPlatform(req.body.idPlatform, req.body.platform);
      if(Sale){
        return res.status(500).send({ error: "Lot already exists"});
      }

      let createLot = await lotDb.post(req.body);
            
      res.status(204).send({message: "Lot created"});
  }catch(err){
      console.log(err);
      return res.status(500).send({error: err});
  }
  
});

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

    try{
        const id = req.params.id;
        let updatedDocument = { ...req.body };        
        delete updatedDocument._id;
        console.log(updatedDocument);
        let result = await lotDb.put(id, updatedDocument);
        console.log(result);
        res.status(200).send(result);
    }catch(err){
        console.log(err);
        return res.status(500).send({error: err});
    }
    
});

exports.delete = asyncHandler(async (req, res, next) => {
  try{
      const id = req.params.id;      

      // Remove the lot
      await lotDb.remove(id);

      res.status(200).send({"message": "Lots deleted"});
  }catch(err){
      console.log(err);
      return res.status(500).send({error: err});
  }
  
});