local db = sqlite("dk")

local username = string.trim(ctx.form.username)
if username == "" or not db:exists("users", "username = :u COLLATE NOCASE", {u = username}) then
	return "username required and must exist"
end

if ctx.form.password == "" then
	return "password required"
end

local user_row = db:get_one("SELECT id, username, password FROM users WHERE username = :u COLLATE NOCASE", {u = username})
if not password_verify(ctx.form.password, user_row.password) then
	return "wrong username or password"
end

local token = generate_token()
local expires = os.time() + (30 * 24 * 60 * 60) -- 30 days
db:insert("user_sessions", {
	user_id = user_row.id,
	token = token,
	expires = expires
})

cookie_set("dkauth", token, { expires = expires })

session_set("logged_in", true)
session_set("user_id", user_row.id)

return "Logged in!"
