package user

import (
	"context"
	"net/http"

	"dev.tandem.ws/tandem/camper/pkg/auth"
	"dev.tandem.ws/tandem/camper/pkg/database"
	httplib "dev.tandem.ws/tandem/camper/pkg/http"
	"dev.tandem.ws/tandem/camper/pkg/locale"
	"dev.tandem.ws/tandem/camper/pkg/template"
)

type AdminHandler struct {
}

func NewAdminHandler() *AdminHandler {
	locale.PgettextNoop("guest", "role")
	locale.PgettextNoop("employee", "role")
	locale.PgettextNoop("admin", "role")

	return &AdminHandler{}
}

func (h *AdminHandler) Handler(user *auth.User, company *auth.Company, conn *database.Conn) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var head string
		head, r.URL.Path = httplib.ShiftPath(r.URL.Path)

		switch head {
		case "":
			switch r.Method {
			case http.MethodGet:
				serveUserIndex(w, r, user, company, conn)
			default:
				httplib.MethodNotAllowed(w, r, http.MethodGet)
			}
		case "login-attempts":
			switch r.Method {
			case http.MethodGet:
				serveLoginAttemptIndex(w, r, user, company, conn)
			default:
				httplib.MethodNotAllowed(w, r, http.MethodGet)
			}
		default:
			http.NotFound(w, r)
		}
	})
}

func serveUserIndex(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, conn *database.Conn) {
	users, err := collectUserEntries(r.Context(), conn)
	if err != nil {
		panic(err)
	}
	page := &userIndex{
		Users: users,
	}
	page.MustRender(w, r, user, company)
}

func collectUserEntries(ctx context.Context, conn *database.Conn) ([]*userEntry, error) {
	rows, err := conn.Query(ctx, `
		select '/admin/users/' || user_id
		     , email
		     , name
		     , role
		from company_user_profile
		order by name
	`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var entries []*userEntry
	for rows.Next() {
		entry := &userEntry{}
		if err = rows.Scan(&entry.URL, &entry.Email, &entry.Name, &entry.Role); err != nil {
			return nil, err
		}
		entries = append(entries, entry)
	}

	return entries, nil
}

type userEntry struct {
	URL   string
	Email string
	Name  string
	Role  string
}

type userIndex struct {
	Users []*userEntry
}

func (page *userIndex) MustRender(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company) {
	template.MustRenderAdmin(w, r, user, company, "user/index.gohtml", page)
}
