import { Req, Res, ReturnValue } from "#/global"
import { LoginUserSchema, RegisterUserSchema, UserSchema } from "@/schema"
import { gFail, gSuccess } from "@/util"
import { auth, config, method, route, validate } from "@noderun/hapi-router"
import * as bcrypt from "bcrypt"
/**
 * 登录界面
 */
export default class {
    @route("/login")
    @auth("try")
    @method("GET")
    async login_GET(request: Req, h: Res): ReturnValue {
        if (request.auth.isAuthenticated) {
            request.yar.flash("warning", "您已经登陆")
            return h.redirect("/")
        } else {
            logger.debug("未登录")
        }
        return h.view("views/login.pug")
    }

    @validate({
        payload: LoginUserSchema,
        $errto: "/login",
        // failAction: 'log'
        failAction: "function",
        failReason: "用户名或密码错误,请重试",
    })
    @method("POST")
    @route("/login")
    async login_POST(request: Req, h: Res): ReturnValue {
        const { username, password, referrer } = request.payload as any

        const User = request.getModel("User")
        const account = <any>await User.findOne({ where: { username: username } })

        if (!account || !(await bcrypt.compare(password, account.password))) {
            request.yar.flash("error", "Invalid username or password")
            return h.redirect("/login")
        }
        request.cookieAuth.set({ id: account.id, nickname: account.nickname })
        request.yar.flash("success", "用户已登录")
        return h.redirect(referrer ? referrer : "/")
    }

    @method("GET")
    @auth()
    async logout(request: Req, h: Res): ReturnValue {
        request.yar.flash("success", "用户已退出")
        request.cookieAuth.clear()
        return h.redirect("/")
    }

    @route("/register")
    @auth("try")
    @method(["POST", "GET"])
    async registerView(request: Req, h: Res): ReturnValue {
        if (request.auth.isAuthenticated) {
            request.yar.flash("warning", "您已经登陆")
            return h.redirect("/")
        } else {
            logger.debug("未登录")
        }
        return h.view("views/register.pug")
    }

    @validate({
        payload: RegisterUserSchema,
        $errto: "/register",
        failAction: "function",
        failReason: "注册账户不符合规范",
    })
    @method("POST")
    async register(request: Req, h: Res): ReturnValue {
        console.log(request);
        let { username, password } = request.payload as any
        const User = request.getModel("User")
        logger.trace("当前注册用户:" + username)
        try {
            const result = await User.findOne({ where: { username: username } })
            if (result != null) {
                request.yar.flash("error", "已存在该用户")
                return h.redirect("/register")
            }
            let salt = bcrypt.genSaltSync(10)
            let pwdLock = bcrypt.hashSync(password, salt)
            await User.create({ username, password: pwdLock })
            request.yar.flash("success", "用户注册成功")
            return h.redirect("/login")
        } catch (e) {
            loggerSite.error(`注册用户失败`, e.message)
            request.yar.flash("error", "注册用户失败")
            return h.redirect("/register")
        }
    }
}