import { Part, createPart } from '../../api/Parts';
import { getSuppliers, createSupplier } from '../../api/Suppliers';
import { PartRequest } from '../RequestForm/RequestForm';
import { parse } from 'tldts';

export const createNewPart = async (partRequest: PartRequest) => {
  let url = partRequest.url.trim();
  if (/^[a-zA-Z]+:\/\//.test(url) == false) {
    url = 'http://' + url;
  }

  const supplierUrl = parse(new URL(url).hostname);

  const supplier_id = await getOrCreateSupplier(
    'http://' + supplierUrl.domain,
    supplierUrl.domainWithoutSuffix as string
  );
  if (!supplier_id) {
    console.error('Error getting or creating supplier');
    return;
  }

  const newPart: Part = {
    url: url,
    supplier_id: supplier_id,
    description: partRequest.description,
    price: partRequest.price,
    part_num: partRequest.part_num,
  };

  try {
    const resultPart = await createPart(newPart);
    return resultPart;
  } catch (error) {
    console.error('Error creating supplier:', error);
    return;
  }
};

export const getOrCreateSupplier = async (
  supplierUrl: string,
  domain: string
) => {
  let supplier;
  try {
    const result = await getSuppliers(supplierUrl);
    supplier = Array.isArray(result) ? result[0] : null;
  } catch (error) {
    console.error('Error fetching supplier:', error);
    return;
  }

  if (!supplier) {
    try {
      supplier = await createSupplier({
        url: supplierUrl,
        name: domain,
      });
    } catch (error) {
      console.error('Error creating supplier:', error);
      return;
    }
  }

  if (supplier && 'supplier_id' in supplier) {
    // supplier is confirmed to be a Supplier
    return supplier.supplier_id;
  } else {
    console.error(
      'Failed to create supplier or supplier is invalid:',
      supplier
    );
    return;
  }
};
