<?php

namespace Velis\Repository\Bpm\Ticket\Post;

use Velis\Arrays;
use Velis\Bpm\Ticket\Post;
use Velis\Bpm\Ticket\Post\File;
use Velis\Bpm\Ticket\Ticket;
use Velis\Db\EntityRepository;
use Velis\Exception as VelisException;

/**
 * @extends EntityRepository<File>
 */
class FileRepository extends EntityRepository
{
    /**
     * @param Ticket[] $tickets
     * @param bool $includePrivate
     * @return File[][]
     * @throws VelisException
     */
    public function findGroupedByTickets(array $tickets, bool $includePrivate): array
    {
        $query = '
            SELECT tpf.*, tp.ticket_id
            FROM app.ticket_post_file_tab tpf
            JOIN app.ticket_post_tab tp USING (ticket_post_id)
            WHERE 1 = 1
        ';

        $params = [
            'tp.ticket_id' => Arrays::getColumn($tickets, 'ticket_id'),
        ];

        $query .= $this->db->conditions($params);

        if (!$includePrivate) {
            $query .= ' AND tp.ticket_post_visibility_id <> :visibility_id';
            $params['visibility_id'] = Post::TYPE_PRIVATE;
        }

        $query .= '
            ORDER BY tp.date_entered, tpf.ticket_post_file_id
        ';

        $rows = $this->db->getAll($query, $params);
        $result = [];

        foreach ($rows as $row) {
            if (!array_key_exists($row['ticket_id'], $result)) {
                $result[$row['ticket_id']] = [];
            }

            $result[$row['ticket_id']][] = $this->createEntityInstance($row);
        }

        return $result;
    }
}
