import {Injectable, ParameterMiddleware, Collection, SecurityContext, Either, ResponseObject, right, Inject} from '@extollo/lib'
import {FeedPost} from '../../../models/FeedPost.model'

/**
 * LoadFeedPosts Middleware
 * --------------------------------------------
 * Load feed posts visible to the user as a handler parameter.
 */
@Injectable()
export class LoadFeedPosts extends ParameterMiddleware<Collection<FeedPost>, [] | [{ all: boolean }]> {
    @Inject()
    protected readonly security!: SecurityContext

    async handle({ all = false } = {}): Promise<Either<ResponseObject, Collection<FeedPost>>> {
        const query = FeedPost.query<FeedPost>()
            .orderByDescending('posted_at')

        if ( !all ) {
            query.limit(6)
        }

        if ( !this.security.hasUser() ) {
            query.where('visible', '=', true)
        }

        return right(await query.get().collect())
    }
}
