<?php

namespace App\Modules\Dashboard\Services;

use App\Models\User;
use App\Modules\Dashboard\Repositories\NotificationCenterRepository;
use App\Support\Bulk\BulkOperationResult;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Notifications\DatabaseNotification;
use Illuminate\Support\Collection;

class NotificationCenterService
{
    public function __construct(
        private readonly NotificationCenterRepository $repo,
    ) {}

    public function unreadCount(User $user): int
    {
        return $this->repo->unreadCount($user);
    }

    /**
     * @return LengthAwarePaginator<int, DatabaseNotification>
     */
    public function paginate(User $user, ?string $category, int $perPage = 20): LengthAwarePaginator
    {
        return $this->repo->paginateForUser($user, $category, $perPage);
    }

    public function markRead(User $user, string $id): bool
    {
        return $this->repo->markAsRead($user, $id);
    }

    public function markAllRead(User $user): void
    {
        $this->repo->markAllRead($user);
    }

    /**
     * @param  list<string>  $ids
     */
    public function markManyRead(User $user, array $ids): BulkOperationResult
    {
        $succeeded = [];
        $failures = [];
        foreach (array_slice($ids, 0, 100) as $raw) {
            $id = (string) $raw;
            if ($this->repo->markAsRead($user, $id)) {
                $succeeded[] = $id;
            } else {
                $failures[] = ['id' => $id, 'message' => __('notifications.bulk_missing')];
            }
        }

        return new BulkOperationResult($succeeded, $failures, __('notifications.bulk_label'));
    }

    /**
     * @return Collection<int, DatabaseNotification>
     */
    public function latestUnread(User $user, int $limit = 6)
    {
        return $this->repo->latestUnread($user, $limit);
    }
}
