package handler

import (
	"errors"
	"fmt"
	"net/http"
)

func (h *Handler) showAdminView(w http.ResponseWriter, r *http.Request) {
	protectClickJacking(w)
	username, err := h.getUser(r)
	if err != nil {
		unauthorized(w, r)
		return
	}
	if username != "aggie" {
		unauthorized(w, r)
		return
	}
	users, err := h.storage.InactiveUsers()
	if err != nil {
		serverError(w, err)
		return
	}
	h.renderLayout(w, "admin", map[string]interface{}{
		"inactive": users,
	}, username)
}

func (h *Handler) activateUser(w http.ResponseWriter, r *http.Request) {
	protectClickJacking(w)
	username, err := h.getUser(r)
	if err != nil {
		unauthorized(w, r)
		return
	}
	if username != "aggie" {
		unauthorized(w, r)
		return
	}
	name := r.URL.Query().Get("name")
	if err := h.storage.ActivateUser(name); err != nil {
		serverError(w, err)
		return
	}
	http.Redirect(w, r, fmt.Sprintf("/admin"), http.StatusFound)
}

func (h *Handler) deleteUser(w http.ResponseWriter, r *http.Request) {
	protectClickJacking(w)
	username, err := h.getUser(r)
	if err != nil {
		unauthorized(w, r)
		return
	}
	if username != "aggie" {
		unauthorized(w, r)
		return
	}
	name := r.URL.Query().Get("name")
	user, err := h.storage.UserByName(name)
	if err != nil {
		serverError(w, err)
		return
	}
	if user.Active {
		serverError(w, errors.New("user is active"))
		return
	}
	if err := h.storage.DeleteUser(name); err != nil {
		serverError(w, err)
		return
	}
	http.Redirect(w, r, fmt.Sprintf("/admin"), http.StatusFound)
}
