import {Middleware, Injectable, Inject, Config, HTTPMethod, Response, HTTPStatus, http, Logging} from '@extollo/lib'

/**
 * CORS Middleware
 * --------------------------------------------
 * Put some description here.
 */
@Injectable()
export class CORS extends Middleware {
    @Inject()
    protected readonly config!: Config

    @Inject()
    protected readonly logging!: Logging

    public async apply() {
        this.logging.debug('CORS Middleware')
        if ( !this.config.get('cors.enable', false) ) {
            this.logging.debug('Will not send CORS headers: CORS is disabled.')
            return
        }

        const response: Response = this.request.response
        response.setHeader('Access-Control-Allow-Headers', '*')

        if ( this.config.get('server.debug', false) ) {
            response.setHeader('Access-Control-Allow-Origin', '*')
            response.setHeader('Access-Control-Allow-Methods', '*')

            if ( this.request.method === 'options' ) {
                return http(HTTPStatus.NO_CONTENT)
            }

            return
        }

        const origins = this.config.get('cors.allow.origins', []) as string[]
        response.setHeader('Access-Control-Allow-Origin', origins.join(','))

        const methods = this.config.get('cors.allow.methods') as HTTPMethod[]
        response.setHeader('Access-Control-Allow-Methods', methods.map(x => x.toUpperCase()).join(','))

        if ( this.request.method === 'options' ) {
            response.setStatus(HTTPStatus.NO_CONTENT)
            return ''
        }
    }
}
