
const express = require('express');
const db = require('../db/models');
const wrapAsync = require('../helpers').wrapAsync;
const passport = require('passport');

const router = express.Router();

router.get('/available', passport.authenticate('jwt', { session: false }), wrapAsync(async (req, res) => {
  const currentUser = req.currentUser;
  const organizationId = currentUser.organizationsId;

  if (!organizationId) {
    return res.status(200).send({ merchants: [], firms: [] });
  }

  // Fetch Merchants in the organization or assigned to user
  const merchants = await db.merchants.findAll({
    where: {
      [db.Sequelize.Op.or]: [
        { organizationsId: organizationId },
        { assigned_accountantId: currentUser.id }
      ]
    }
  });

  // Fetch Firms in the organization
  const firms = await db.firms.findAll({
    where: {
      organizationsId: organizationId
    }
  });

  res.status(200).send({
    merchants: merchants.map(m => ({
      id: m.id,
      name: m.business_name,
      type: 'merchant',
      registration: m.tin_number
    })),
    firms: firms.map(f => ({
      id: f.id,
      name: f.name,
      type: 'firm',
      registration: f.tax_id_number
    }))
  });
}));

module.exports = router;
