const Unit = require('libflitter/Unit')
const cors = require('cors')

class CORSUnit extends Unit {
    static get services() {
        return [...super.services, 'output']
    }

    static get name() {
        return 'cors'
    }

    async go(app) {
        app.express.use(cors({
            origin: (origin, callback) => {
                const allowed = [
                    'https://noded.garrettmills.dev',
                    'https://noded-dev.garrettmills.dev',
                    'http://noded.garrettmills.dev',
                    'http://noded-dev.garrettmills.dev',
                    'http://localhost:8000',
                    'http://localhost:8100'
                ]

                if ( allowed.includes(origin) || !origin ) callback(null, true)
                else callback(new Error('Invalid origin.'))
            }
        }))
    }
}

module.exports = exports = CORSUnit
