<?php
/***********************************************************************************
 * The contents of this file are subject to the Extension License Agreement
 * ("Agreement") which can be viewed at
 * https://www.espocrm.com/extension-license-agreement/.
 * By copying, installing downloading, or using this file, You have unconditionally
 * agreed to the terms and conditions of the Agreement, and You may not use this
 * file except in compliance with the Agreement. Under the terms of the Agreement,
 * You shall not license, sublicense, sell, resell, rent, lease, lend, distribute,
 * redistribute, market, publish, commercialize, or otherwise transfer rights or
 * usage to the software or any modified version or derivative work of the software
 * created by or for you.
 *
 * Copyright (C) 2024-2025 Letrium Ltd.
 *
 * License ID: f27e70ce6801a13265271f5669c8bc5c
 ************************************************************************************/

namespace Espo\Modules\Project\Tools\Column;

use Espo\Core\Exceptions\Forbidden;
use Espo\Modules\Project\Entities\ProjectColumn;
use Espo\Modules\Project\Entities\ProjectTask;
use Espo\ORM\EntityManager;
use RuntimeException;

class MoveService
{
    public function __construct(
        private EntityManager $entityManager,
    ) {}

    /**
     * @throws Forbidden
     */
    public function moveUp(ProjectColumn $column): void
    {
        $columns = $this->getColumns($column);
        $index = $this->getIndex($columns, $column);

        $anotherColumn = $columns[$index - 1] ?? null;

        if (!$anotherColumn) {
            throw new Forbidden("Can't move first.");
        }

        $this->swapColumns($anotherColumn, $column);
    }

    /**
     * @throws Forbidden
     */
    public function moveDown(ProjectColumn $column): void
    {
        $columns = $this->getColumns($column);
        $index = $this->getIndex($columns, $column);

        $anotherColumn = $columns[$index + 1] ?? null;

        if (!$anotherColumn) {
            throw new Forbidden("Can't move last.");
        }

        $this->swapColumns($anotherColumn, $column);
    }

    /**
     * @throws Forbidden
     */
    private function swapColumns(ProjectColumn $anotherColumn, ProjectColumn $column): void
    {
        if (
            $anotherColumn->getMappedStatus() !== $column->getMappedStatus() &&
            $column->getMappedStatus() !== ProjectTask::STATUS_DEFERRED
        ) {
            throw new Forbidden("Can't break status order.");
        }

        $order = $column->getOrder();
        $column->setOrder($anotherColumn->getOrder());
        $anotherColumn->setOrder($order);

        $this->entityManager->saveEntity($column);
        $this->entityManager->saveEntity($anotherColumn);
    }

    /**
     * @return ProjectColumn[]
     */
    private function getColumns(ProjectColumn $column): array
    {
        $collection = $this->entityManager
            ->getRDBRepositoryByClass(ProjectColumn::class)
            ->where(['boardId' => $column->getBoardId()])
            ->order('order')
            ->find();

        return iterator_to_array($collection);
    }

    /**
     * @param ProjectColumn[] $columns
     */
    private function getIndex(array $columns, ProjectColumn $column): int
    {
        $index = -1;

        foreach ($columns as $i => $it) {
            if ($it->getId() === $column->getId()) {
                $index = $i;

                break;
            }
        }

        if ($index < 0) {
            throw new RuntimeException("Column not found.");
        }

        return $index;
    }
}
