import {
    Either,
    http,
    HTTPStatus,
    Inject,
    Injectable,
    left,
    ParameterMiddleware,
    ResponseObject, right,
    SecurityContext,
} from '@extollo/lib'
import {Snippet} from '../../../models/Snippet.model'

/**
 * LoadSnippet Middleware
 * --------------------------------------------
 * Look up the Snippet instance from the request parameters.
 */
@Injectable()
export class LoadSnippet extends ParameterMiddleware<Snippet> {
    @Inject()
    protected readonly security!: SecurityContext

    async handle(): Promise<Either<ResponseObject, Snippet>> {
        const slug = String(this.request.input('slug') || '')
        if ( !slug ) {
            return left(http(HTTPStatus.http404))
        }

        const snippet = await Snippet.query<Snippet>()
            .where('slug', '=', slug)
            .first()

        if ( !snippet || snippet.usersOnly && !this.security.hasUser() ) {
            return left(http(HTTPStatus.http404))
        }

        return right(snippet)
    }
}
