export function validateAuthFields({ username, password }) {
  const errors = {}

  if (!username || username.trim().length < 3) errors.username = 'Username must be at least 3 characters.'
  if (!password || password.length < 6) errors.password = 'Password must be at least 6 characters.'

  return errors
}

export function validateNonEmpty(label, value, errors, key = label) {
  if (value === undefined || value === null || String(value).trim() === '') {
    errors[key] = `${label} is required.`
  }
}

export function parseNumber(value) {
  if (value === '' || value === undefined || value === null) return NaN
  const n = Number(value)
  return Number.isFinite(n) ? n : NaN
}

export function isValidDateInput(value) {
  if (!value) return false
  const d = new Date(value)
  return !Number.isNaN(d.getTime())
}

export function validateProductForm(form) {
  const errors = {}
  if (!form.productCode) errors.productCode = 'Product Code is required.'
  if (!form.productName) errors.productName = 'Product Name is required.'
  if (!form.category) errors.category = 'Category is required.'
  if (!form.supplierName) errors.supplierName = 'Supplier Name is required.'

  const qty = parseNumber(form.quantityInStock)
  if (Number.isNaN(qty) || qty < 0) errors.quantityInStock = 'Quantity In Stock must be a valid number (0 or greater).'

  const price = parseNumber(form.unitPrice)
  if (Number.isNaN(price) || price < 0) errors.unitPrice = 'Unit Price must be a valid number (0 or greater).'

  if (!form.dateReceived || !isValidDateInput(form.dateReceived)) errors.dateReceived = 'Date Received must be a valid date.'

  return errors
}

export function validateWarehouseForm(form) {
  const errors = {}
  if (!form.warehouseCode) errors.warehouseCode = 'Warehouse Code is required.'
  if (!form.warehouseName) errors.warehouseName = 'Warehouse Name is required.'
  if (!form.warehouseLocation) errors.warehouseLocation = 'Warehouse Location is required.'
  return errors
}

export function validateTransactionForm(form) {
  const errors = {}
  if (!form.product) errors.product = 'Product is required.'
  if (!form.warehouse) errors.warehouse = 'Warehouse is required.'

  const qty = parseNumber(form.quantityMoved)
  if (Number.isNaN(qty) || qty <= 0) errors.quantityMoved = 'Quantity Moved must be a positive number.'

  if (form.transactionType !== 'Stock In' && form.transactionType !== 'Stock Out') {
    errors.transactionType = 'Transaction Type must be Stock In or Stock Out.'
  }

  if (form.transactionDate && !isValidDateInput(form.transactionDate)) {
    errors.transactionDate = 'Transaction Date must be a valid date.'
  }

  return errors
}

