import {Controller, ErrorWithContext, http, HTTPStatus, Inject, Injectable, json, Routing} from '@extollo/lib'
import {User} from '../../../models/User.model'

@Injectable()
export class Webfinger extends Controller {
    @Inject()
    protected readonly routing!: Routing

    async getUser() {
        const username = this.request.safe('username').string()

        // @ts-ignore
        const user = await User.query<User>()
            .where('username', '=', username)
            .first()

        if ( !user ) {
            return http(HTTPStatus.NOT_FOUND)
        }

        return json(await user.toPub())
    }

    async getWebfinger() {
        const host = new URL(this.routing.getAppUrl().toRemote).host
        const resource = this.request.safe('resource').string()
        if ( !resource.startsWith('acct:') || !resource.endsWith(`@${host}`) ) {
            throw new ErrorWithContext('Invalid webfinger resource query', { resource })
        }

        const username = resource.slice('acct:'.length, -(`@${host}`.length))
        // @ts-ignore
        const user = await User.query<User>()
            .where('username', '=', username)
            .first()

        if ( !user ) {
            return http(HTTPStatus.NOT_FOUND)
        }

        return json(await user.toWebfinger())
    }

}
