const { Model } = require('flitter-orm')
const uuid = require('uuid').v4

class ClientModel extends Model {
    static get services() {
        return [...super.services, 'models']
    }

    static get schema() {
        return {
            payload: {
                client_id: { type: String, default: uuid },
                client_secret: { type: String, default: uuid },
                client_name: String,
                grant_types: [String],
                redirect_uris: [String],
            },
        }
    }

    to_api() {
        const vals = ['client_id', 'client_secret', 'client_name', 'grant_types']
        const val = {}
        for ( const item of vals ) {
            val[item] = this.payload[item]
        }
        val.redirect_uri = this.payload?.redirect_uris?.[0]
        val.id = this.id
        return val
    }

    async save() {
        await super.save()
        this.payload.client_id = this.id
        return super.save()
    }

    async application() {
        const Application = this.models.get('Application')
        return Application.findOne({ active: true, oauth_client_ids: this.id })
    }
}

module.exports = exports = ClientModel
