'use strict';

async function hydrateColumnsWithTasks(adapter, board) {
  const columnIds = (board.column || []).map((c) => c.id);
  const tasksByColumn = /* @__PURE__ */ new Map();
  if (columnIds.length > 0) {
    const taskResults = await Promise.all(
      columnIds.map(
        (columnId) => adapter.findMany({
          model: "kanbanTask",
          where: [
            { field: "columnId", value: columnId, operator: "eq" }
          ],
          sortBy: { field: "order", direction: "asc" }
        })
      )
    );
    for (let i = 0; i < columnIds.length; i++) {
      const columnId = columnIds[i];
      const tasks = taskResults[i];
      if (columnId && tasks) {
        tasksByColumn.set(columnId, tasks);
      }
    }
  }
  const columns = (board.column || []).sort((a, b) => a.order - b.order).map((col) => ({ ...col, tasks: tasksByColumn.get(col.id) || [] }));
  const { column: _, ...boardWithoutJoin } = board;
  return { ...boardWithoutJoin, columns };
}
async function getAllBoards(adapter, params) {
  const query = params ?? {};
  const whereConditions = [];
  if (query.slug) {
    whereConditions.push({
      field: "slug",
      value: query.slug,
      operator: "eq"
    });
  }
  if (query.ownerId) {
    whereConditions.push({
      field: "ownerId",
      value: query.ownerId,
      operator: "eq"
    });
  }
  if (query.organizationId) {
    whereConditions.push({
      field: "organizationId",
      value: query.organizationId,
      operator: "eq"
    });
  }
  const where = whereConditions.length > 0 ? whereConditions : void 0;
  const [boards, total] = await Promise.all([
    adapter.findMany({
      model: "kanbanBoard",
      limit: query.limit ?? 50,
      offset: query.offset ?? 0,
      where,
      sortBy: { field: "createdAt", direction: "desc" },
      join: { kanbanColumn: true }
    }),
    adapter.count({ model: "kanbanBoard", where })
  ]);
  const items = await Promise.all(
    boards.map((board) => hydrateColumnsWithTasks(adapter, board))
  );
  return { items, total, limit: query.limit, offset: query.offset };
}
async function getBoardById(adapter, id) {
  const board = await adapter.findOne({
    model: "kanbanBoard",
    where: [{ field: "id", value: id, operator: "eq" }],
    join: { kanbanColumn: true }
  });
  if (!board) {
    return null;
  }
  return hydrateColumnsWithTasks(adapter, board);
}

exports.getAllBoards = getAllBoards;
exports.getBoardById = getBoardById;
