{"size": 1281, "ext": "js", "max_stars_repo_path": "src/modules/debt/functions/editDebt.js", "max_stars_repo_name": "quienmedebe/api-rest", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/modules/debt/functions/editDebt.js", "max_issues_repo_name": "quienmedebe/api-rest", "max_issues_repo_issues_event_min_datetime": "2020-09-26T17:50:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T14:28:03.000Z", "max_forks_repo_path": "src/modules/debt/functions/editDebt.js", "max_forks_repo_name": "quienmedebe/api-rest", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 93, "max_forks_count": null, "avg_line_length": 26.1428571429, "max_line_length": 93, "alphanum_fraction": 0.6541764247}
const Ajv = require('ajv');
const validation = require('../validation');
const Database = require('../../../database');
const ERRORS = require('../errors');

async function editDebt({accountId, debtId, amount, type, status} = {}) {
  const ajv = new Ajv({allErrors: true});
  const areParametersCorrect = ajv.validate(
    {
      type: 'object',
      required: ['accountId', 'debtId'],
      properties: {
        accountId: validation.accountIdSchema,
        debtId: validation.publicIdSchema,
        amount: validation.amountSchema,
        type: validation.typeSchema,
        status: validation.statusSchema,
      },
    },
    {accountId, debtId, amount, type, status}
  );

  const isAmountUndefined = typeof amount === 'undefined';
  const isTypeUndefined = typeof type === 'undefined';
  const isStatusUndefined = typeof status === 'undefined';

  if (!areParametersCorrect || (isAmountUndefined && isTypeUndefined && isStatusUndefined)) {
    throw new Error('Some arguments are invalid');
  }

  const [numberOfUpdatedRows] = await Database.functions.debt.editDebt({
    accountId,
    debtId,
    amount,
    type,
    status,
  });

  if (!numberOfUpdatedRows) {
    return ERRORS.DEBT_NOT_FOUND;
  }

  return {
    id: debtId,
  };
}

module.exports = editDebt;
