import * as fs from "fs";
import path from "path";
import { AllbidsApiBid } from "../models/allbids.com.au/allbids-api-bid.js";
import { AllbidsProductBid } from "../models/allbids.com.au/allbids-product-bid.js";
import { GrayApiBid } from "../models/grays.com/grays-api-bid.js";
import { GraysProductBid } from "../models/grays.com/grays-product-bid.js";
import { LangtonsApiBid } from "../models/langtons.com.au/langtons-api-bid.js";
import { LangtonsProductBid } from "../models/langtons.com.au/langtons-product-bid.js";
import { LawsonsApiBid } from "../models/lawsons.com.au/lawsons-api-bid.js";
import { LawsonsProductBid } from "../models/lawsons.com.au/lawsons-product-bid.js";
import { PicklesApiBid } from "../models/pickles.com.au/pickles-api-bid.js";
import { PicklesProductBid } from "../models/pickles.com.au/pickles-product-bid.js";
import configs from "../system/config.js";
import CONSTANTS from "../system/constants.js";
import { sanitizeFileName } from "../system/utils.js";

// Time to update
const TIME = 30 * 1000;

export const handleCloseRemoveProduct = (data) => {
  if (!Array.isArray(data)) return;

  data.forEach(async (item) => {
    if (item.page_context) {
      safeClosePage(item);
    }
  });
};

export const createBidProduct = (web, data) => {
  switch (web.origin_url) {
    case configs.WEB_URLS.GRAYS: {
      return new GraysProductBid({ ...data });
    }
    case configs.WEB_URLS.LANGTONS: {
      return new LangtonsProductBid({ ...data });
    }
    case configs.WEB_URLS.LAWSONS: {
      return new LawsonsProductBid({ ...data });
    }
    case configs.WEB_URLS.PICKLES: {
      return new PicklesProductBid({ ...data });
    }
    case configs.WEB_URLS.ALLBIDS: {
      return new AllbidsProductBid({ ...data });
    }
  }
};

export const createApiBid = (web) => {
  switch (web.origin_url) {
    case configs.WEB_URLS.GRAYS: {
      return new GrayApiBid({ ...web });
    }
    case configs.WEB_URLS.LANGTONS: {
      return new LangtonsApiBid({ ...web });
    }
    case configs.WEB_URLS.LAWSONS: {
      return new LawsonsApiBid({ ...web });
    }
    case configs.WEB_URLS.PICKLES: {
      return new PicklesApiBid({ ...web });
    }
    case configs.WEB_URLS.ALLBIDS: {
      return new AllbidsApiBid({ ...web });
    }
  }
};

export const deleteProfile = (data) => {
  if (!data?.origin_url) return false;
  const filePath = path.join(
    CONSTANTS.PROFILE_PATH,
    sanitizeFileName(data?.origin_url) + ".json"
  );

  if (fs.existsSync(filePath)) {
    fs.unlinkSync(filePath);
    return true;
  }

  return false;
};

export const shouldUpdateProductTab = (productTab) => {
  const updatedAt = new Date(productTab.updated_at).getTime();
  const now = Date.now();

  return now - updatedAt >= TIME;
};
