package auth

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"html/template"
	"net/http"
	"net/url"
	"strings"
	"time"

	"crypto/sha256"
	"code.secondbit.org/pass"
	"code.secondbit.org/uuid"
)

const (
	authCookieName         = "auth"
	defaultGrantExpiration = 600 // default to ten minute grant expirations
	getGrantTemplateName   = "get_grant"
)

var (
	// ErrNoAuth is returned when an Authorization header is not present or is empty.
	ErrNoAuth = errors.New("no authorization header supplied")
	// ErrInvalidAuthFormat is returned when an Authorization header is present but not the correct format.
	ErrInvalidAuthFormat = errors.New("authorization header is not in a valid format")
	// ErrIncorrectAuth is returned when a user authentication attempt does not match the stored values.
	ErrIncorrectAuth = errors.New("invalid authentication")
	// ErrInvalidPassphraseScheme is returned when an undefined passphrase scheme is used.
	ErrInvalidPassphraseScheme = errors.New("invalid passphrase scheme")
	// ErrNoSession is returned when no session ID is passed with a request.
	ErrNoSession = errors.New("no session ID found")
)

type tokenResponse struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type,omitempty"`
	ExpiresIn    int32  `json:"expires_in,omitempty"`
	RefreshToken string `json:"refresh_token,omitempty"`
}

func getBasicAuth(r *http.Request) (un, pass string, err error) {
	auth := r.Header.Get("Authorization")
	if auth == "" {
		return "", "", ErrNoAuth
	}
	pieces := strings.SplitN(auth, " ", 2)
	if pieces[0] != "Basic" {
		return "", "", ErrInvalidAuthFormat
	}
	decoded, err := base64.StdEncoding.DecodeString(pieces[1])
	if err != nil {
		// TODO(paddy): should probably log this...
		return "", "", ErrInvalidAuthFormat
	}
	info := strings.SplitN(string(decoded), ":", 2)
	return info[0], info[1], nil
}

func checkCookie(r *http.Request, context Context) (Session, error) {
	cookie, err := r.Cookie(authCookieName)
	if err != nil {
		if err == http.ErrNoCookie {
			return Session{}, ErrNoSession
		}
		return Session{}, err
	}
	if cookie.Name != authCookieName || !cookie.Expires.After(time.Now()) ||
		!cookie.Secure || !cookie.HttpOnly {
		return Session{}, ErrInvalidSession
	}
	sess, err := context.GetSession(cookie.Value)
	if err == ErrSessionNotFound {
		return Session{}, ErrInvalidSession
	} else if err != nil {
		return Session{}, err
	}
	if !sess.Active {
		return Session{}, ErrInvalidSession
	}
	return sess, nil
}

func authenticate(user, passphrase string, context Context) (Profile, error) {
	profile, err := context.GetProfileByLogin(user)
	if err != nil {
		if err == ErrProfileNotFound {
			return Profile{}, ErrIncorrectAuth
		}
		return Profile{}, err
	}
	switch profile.PassphraseScheme {
	case 1:
		candidate := pass.Check(sha256.New, profile.Iterations, []byte(passphrase), []byte(profile.Salt))
		if !pass.Compare(candidate, []byte(profile.Passphrase)) {
			return Profile{}, ErrIncorrectAuth
		}
	default:
		// TODO(paddy): return some error
		return Profile{}, ErrInvalidPassphraseScheme
	}
	return profile, nil
}

// GetGrantHandler presents and processes the page for asking a user to grant access
// to their data. See RFC 6749, Section 4.1.
func GetGrantHandler(w http.ResponseWriter, r *http.Request, context Context) {
	session, err := checkCookie(r, context)
	if err != nil {
		if err == ErrNoSession {
			// TODO(paddy): redirect to login screen
			//return
		}
		if err == ErrInvalidSession {
			// TODO(paddy): return an access denied error
			//return
		}
		// TODO(paddy): return a server error
		//return
	}
	if r.URL.Query().Get("client_id") == "" {
		w.WriteHeader(http.StatusBadRequest)
		context.Render(w, getGrantTemplateName, map[string]interface{}{
			"error": template.HTML("Client ID must be specified in the request."),
		})
		return
	}
	clientID, err := uuid.Parse(r.URL.Query().Get("client_id"))
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		context.Render(w, getGrantTemplateName, map[string]interface{}{
			"error": template.HTML("client_id is not a valid Client ID."),
		})
		return
	}
	redirectURI := r.URL.Query().Get("redirect_uri")
	redirectURL, err := url.Parse(redirectURI)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		context.Render(w, getGrantTemplateName, map[string]interface{}{
			"error": template.HTML("The redirect_uri specified is not valid."),
		})
		return
	}
	client, err := context.GetClient(clientID)
	if err != nil {
		if err == ErrClientNotFound {
			w.WriteHeader(http.StatusBadRequest)
			context.Render(w, getGrantTemplateName, map[string]interface{}{
				"error": template.HTML("The specified Client couldn&rsquo;t be found."),
			})
		} else {
			w.WriteHeader(http.StatusInternalServerError)
			context.Render(w, getGrantTemplateName, map[string]interface{}{
				"internal_error": template.HTML(err.Error()),
			})
		}
		return
	}
	// whether a redirect URI is valid or not depends on the number of endpoints
	// the client has registered
	numEndpoints, err := context.CountEndpoints(clientID)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		context.Render(w, getGrantTemplateName, map[string]interface{}{
			"internal_error": template.HTML(err.Error()),
		})
		return
	}
	var validURI bool
	if redirectURI != "" {
		// BUG(paddy): We really should normalize URIs before trying to compare them.
		validURI, err = context.CheckEndpoint(clientID, redirectURI)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			context.Render(w, getGrantTemplateName, map[string]interface{}{
				"internal_error": template.HTML(err.Error()),
			})
			return
		}
	} else if redirectURI == "" && numEndpoints == 1 {
		// if we don't specify the endpoint and there's only one endpoint, the
		// request is valid, and we're redirecting to that one endpoint
		validURI = true
		endpoints, err := context.ListEndpoints(clientID, 1, 0)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			context.Render(w, getGrantTemplateName, map[string]interface{}{
				"internal_error": template.HTML(err.Error()),
			})
			return
		}
		if len(endpoints) != 1 {
			validURI = false
		} else {
			u := endpoints[0].URI // Copy it here to avoid grabbing a pointer to the memstore
			redirectURI = u.String()
			redirectURL = &u
		}
	} else {
		validURI = false
	}
	if !validURI {
		w.WriteHeader(http.StatusBadRequest)
		context.Render(w, getGrantTemplateName, map[string]interface{}{
			"error": template.HTML("The redirect_uri specified is not valid."),
		})
		return
	}
	scope := r.URL.Query().Get("scope")
	state := r.URL.Query().Get("state")
	if r.URL.Query().Get("response_type") != "code" {
		q := redirectURL.Query()
		q.Add("error", "invalid_request")
		q.Add("state", state)
		redirectURL.RawQuery = q.Encode()
		http.Redirect(w, r, redirectURL.String(), http.StatusFound)
		return
	}
	if r.Method == "POST" {
		// BUG(paddy): We need to implement CSRF protection when obtaining a grant code.
		if r.PostFormValue("grant") == "approved" {
			code := uuid.NewID().String()
			grant := Grant{
				Code:        code,
				Created:     time.Now(),
				ExpiresIn:   defaultGrantExpiration,
				ClientID:    clientID,
				Scope:       scope,
				RedirectURI: r.URL.Query().Get("redirect_uri"),
				State:       state,
				ProfileID:   session.ProfileID,
			}
			err := context.SaveGrant(grant)
			if err != nil {
				q := redirectURL.Query()
				q.Add("error", "server_error")
				q.Add("state", state)
				redirectURL.RawQuery = q.Encode()
				http.Redirect(w, r, redirectURL.String(), http.StatusFound)
				return
			}
			q := redirectURL.Query()
			q.Add("code", code)
			q.Add("state", state)
			redirectURL.RawQuery = q.Encode()
			http.Redirect(w, r, redirectURL.String(), http.StatusFound)
			return
		}
		q := redirectURL.Query()
		q.Add("error", "access_denied")
		q.Add("state", state)
		redirectURL.RawQuery = q.Encode()
		http.Redirect(w, r, redirectURL.String(), http.StatusFound)
		return
	}
	w.WriteHeader(http.StatusOK)
	context.Render(w, getGrantTemplateName, map[string]interface{}{
		"client": client,
	})
}

// GetTokenHandler allows a client to exchange an authorization grant for an
// access token. See RFC 6749 Section 4.1.3.
func GetTokenHandler(w http.ResponseWriter, r *http.Request, context Context) {
	enc := json.NewEncoder(w)
	grantType := r.PostFormValue("grant_type")
	if grantType != "authorization_code" {
		// TODO(paddy): render invalid request JSON
		return
	}
	code := r.PostFormValue("code")
	if code == "" {
		// TODO(paddy): render invalid request JSON
		return
	}
	redirectURI := r.PostFormValue("redirect_uri")
	clientIDStr, clientSecret, err := getBasicAuth(r)
	if err != nil {
		// TODO(paddy): render access denied
		return
	}
	if clientIDStr == "" && err == nil {
		clientIDStr = r.PostFormValue("client_id")
	}
	// TODO(paddy): client ID can also come from Basic auth
	clientID, err := uuid.Parse(clientIDStr)
	if err != nil {
		// TODO(paddy): render invalid request JSON
		return
	}
	client, err := context.GetClient(clientID)
	if err != nil {
		if err == ErrClientNotFound {
			// TODO(paddy): render invalid request JSON
		} else {
			// TODO(paddy): render internal server error JSON
		}
		return
	}
	if client.Secret != clientSecret {
		// TODO(paddy): render invalid request JSON
		return
	}
	grant, err := context.GetGrant(code)
	if err != nil {
		if err == ErrGrantNotFound {
			// TODO(paddy): return error
			return
		}
		// TODO(paddy): return error
	}
	if grant.RedirectURI != redirectURI {
		// TODO(paddy): return error
	}
	if !grant.ClientID.Equal(clientID) {
		// TODO(paddy): return error
	}
	token := Token{
		AccessToken:  uuid.NewID().String(),
		RefreshToken: uuid.NewID().String(),
		Created:      time.Now(),
		ExpiresIn:    defaultTokenExpiration,
		TokenType:    "", // TODO(paddy): fill in token type
		Scope:        grant.Scope,
		ProfileID:    grant.ProfileID,
	}
	err = context.SaveToken(token)
	if err != nil {
		// TODO(paddy): return error
	}
	resp := tokenResponse{
		AccessToken:  token.AccessToken,
		RefreshToken: token.RefreshToken,
		ExpiresIn:    token.ExpiresIn,
		TokenType:    token.TokenType,
	}
	err = enc.Encode(resp)
	if err != nil {
		// TODO(paddy): log this or something
		return
	}
}

// TODO(paddy): exchange user credentials for access token
// TODO(paddy): exchange client credentials for access token
// TODO(paddy): implicit grant for access token
// TODO(paddy): exchange refresh token for access token
