package auth

import (
	"errors"
	"net/http"
	"time"

	"secondbit.org/uuid"
)

const sessionCookie = "session"

var (
	ErrSessionNotFound = errors.New("Session not found.")
)

type Session struct {
	Token   string
	User    uuid.ID
	Expires time.Time
	Created time.Time
	IP      string
}

func validateSession(r *http.Request, c Context) error {
	cookie, err := r.Cookie(sessionCookie)
	if err == http.ErrNoCookie {
		return ErrSessionNotFound
	}
	_, err = c.Sessions.GetSession(cookie.Value)
	return err
}

func HandleLoginRequest(w http.ResponseWriter, r *http.Request, ctx Context) {
	if r.Method == "GET" {
		ctx.RenderLogin(w, r)
		return
	} else if r.Method != "POST" {
		// TODO: return bad method error
		return
	}

	if r.FormValue("username") == "" || r.FormValue("password") == "" {
		// TODO: return unauthenticated error
		return
	}
	id, err := ctx.Profiles.GetProfile(r.FormValue("username"), r.FormValue("password"))
	if err != nil {
		if err == ErrProfileNotFound {
			// TODO: return unauthenticated error
			return
		}
		// TODO: return internal server error
		return
	}
	session := Session{
		Token:   newToken(),
		User:    id,
		Expires: time.Now().Add(ctx.Config.SessionLength),
		Created: time.Now(),
		IP:      r.Header.Get(ctx.Config.RequestIPHeader),
	}
	err = ctx.Sessions.SetSession(session)
	if err != nil {
		// TODO: return internal server error
		return
	}
	http.SetCookie(w, &http.Cookie{
		Name:     sessionCookie,
		Value:    session.Token,
		Expires:  session.Expires,
		Secure:   true,
		HttpOnly: true,
	})
	// TODO: redirect
}
