const express = require('express');

const db = require('../db/models');
const OrganizationsDBApi = require('../db/api/organizations');
const wrapAsync = require('../helpers').wrapAsync;

const router = express.Router();

async function loadLinkedTenantsForOrganization(organizationId) {
  const linkedTenants = await db.tenants.findAll({
    attributes: ['id', 'name', 'slug', 'primary_domain', 'timezone', 'default_currency', 'is_active'],
    include: [
      {
        model: db.organizations,
        as: 'organizations_filter',
        required: true,
        attributes: [],
        through: { attributes: [] },
        where: { id: organizationId },
      },
    ],
    limit: 3,
    order: [['name', 'asc']],
  });

  return linkedTenants.map((tenant) => tenant.get({ plain: true }));
}

/**
 *  @swagger
 *  /api/organizations:
 *    get:
 *      security:
 *        - bearerAuth: []
 *      tags: [Organizations]
 *      summary: Get all organizations
 *      description: Get all organizations
 *      responses:
 *        200:
 *          description: Organizations list successfully received
 *          content:
 *            application/json:
 *              schema:
 *                type: array
 *                items:
 *                  $ref: "#/components/schemas/Organizations"
 *        401:
 *          $ref: "#/components/responses/UnauthorizedError"
 *        404:
 *          description: Data not found
 *        500:
 *          description: Some server error
 */
router.get(
  '/',
  wrapAsync(async (req, res) => {
    const payload = await OrganizationsDBApi.findAll(req.query || {}, true, {});

    const simplifiedPayload = await Promise.all(
      (payload.rows || []).map(async (org) => {
        const linkedTenants = await loadLinkedTenantsForOrganization(org.id);

        return {
          id: org.id,
          name: org.name,
          linkedTenants,
          linkedTenantNames: linkedTenants
            .map((tenant) => tenant.name)
            .filter(Boolean),
          primaryTenant: linkedTenants[0] || null,
        };
      }),
    );

    res.status(200).send(simplifiedPayload);
  }),
);

module.exports = router;
