<?php

namespace FSPoster\App\TelegramNotification\App\Repositories;

use FSPoster\App\Models\Channel;
use FSPoster\App\Models\ChannelSession;

class TelegramNotificationRepository
{
    public function getActiveChannels(): array
    {
        $telegramSessions = ChannelSession::where('social_network', 'telegram')->select('id');

        $channels = Channel::withoutGlobalScope('my_channels')
            ->where('channel_session_id', 'in', $telegramSessions)
            ->where('status', 1)
            ->fetchAll();

        return $channels ?: [];
    }

    /**
     * @param int[] $ids
     * @return array<int, \FSPoster\App\Providers\DB\Collection> keyed by channel id
     */
    public function getChannelsByIds(array $ids): array
    {
        if (empty($ids)) {
            return [];
        }

        $rows = Channel::withoutGlobalScope('my_channels')
            ->where('id', 'in', $ids)
            ->where('status', 1)
            ->fetchAll();

        $map = [];
        foreach ($rows ?: [] as $row) {
            $map[(int) $row->id] = $row;
        }

        return $map;
    }

    /**
     * @param int[] $ids
     * @return array<int, \FSPoster\App\Providers\DB\Collection> keyed by session id
     */
    public function getSessionsByIds(array $ids): array
    {
        if (empty($ids)) {
            return [];
        }

        $rows = ChannelSession::where('id', 'in', $ids)->fetchAll();

        $map = [];
        foreach ($rows ?: [] as $row) {
            $map[(int) $row->id] = $row;
        }

        return $map;
    }
}
