import {
    Either, hasOwnProperty,
    http,
    HTTPStatus,
    Inject,
    Injectable,
    left, Logging,
    ParameterMiddleware,
    ResponseObject,
    right,
} from '@extollo/lib'
import {ContactForm} from '../../../types/ContactForm.type'

/**
 * ContactForm Middleware
 * --------------------------------------------
 * Parse the contact form data and validate it. Provide the fields as middleware.
 */
@Injectable()
export class ValidContactForm extends ParameterMiddleware<ContactForm> {
    @Inject()
    protected readonly logging!: Logging

    async handle(): Promise<Either<ResponseObject, ContactForm>> {
        const allInput = this.request.input()
        if ( typeof allInput !== 'object' || allInput === null || !hasOwnProperty(allInput, 'e-mail') || allInput['e-mail'] ) {
            return left(http(HTTPStatus.UNAUTHORIZED))
        }

        return right({
            email: this.request.safe('email').present().string(),
            name: this.request.safe('name').present().string(),
            message: this.request.safe('message').present().string(),
        })
    }
}
