package api

import (
	"errors"
	"net/http"
	"strings"

	"party.at/party/internal/data"
	"party.at/party/internal/validator"
)

func (api *Api) CreateAuthenticationToken(w http.ResponseWriter, r *http.Request) {
	var input struct {
		Email    string `json:"email"`
		Password string `json:"password"`
	}

	if err := api.readJSON(w, r, &input); err != nil {
		api.BadRequestResponse(w, r, err)
		return
	}

	v := validator.New()
	v.Check(input.Email != "", "email", "must be provided")
	v.Check(input.Password != "", "password", "must be provided")
	if !v.Valid() {
		api.FailedValidationResponse(w, r, v.Errors)
		return
	}

	token, err := api.App.LoginUser(input.Email, input.Password)
	if err != nil {
		switch {
		case errors.Is(err, data.ErrInvalidCredentials):
			api.InvalidCredentialsResponse(w, r)
		default:
			api.ServerErrorResponse(w, r, err)
		}
		return
	}

	if err = api.writeJSON(w, http.StatusCreated, envelope{"authentication_token": token}, nil); err != nil {
		api.ServerErrorResponse(w, r, err)
	}
}

func (api *Api) DeleteAuthenticationToken(w http.ResponseWriter, r *http.Request) {
	authHeader := r.Header.Get("Authorization")
	parts := strings.Split(authHeader, " ")
	if len(parts) != 2 || parts[0] != "Bearer" {
		api.InvalidAuthenticationTokenResponse(w, r)
		return
	}

	token := parts[1]
	v := validator.New()
	if data.ValidateTokenPlaintext(v, token); !v.Valid() {
		api.InvalidAuthenticationTokenResponse(w, r)
		return
	}

	if err := api.App.DeleteToken(token); err != nil {
		api.ServerErrorResponse(w, r, err)
		return
	}

	if err := api.writeJSON(w, http.StatusOK, envelope{"message": "authentication token successfully deleted"}, nil); err != nil {
		api.ServerErrorResponse(w, r, err)
	}
}
