package user

import (
	"context"
	"net/http"
	"time"

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

func serveLoginAttemptIndex(w http.ResponseWriter, r *http.Request, loginAttempt *auth.User, company *auth.Company, conn *database.Conn) {
	loginAttempts, err := collectLoginAttemptEntries(r.Context(), conn)
	if err != nil {
		panic(err)
	}
	loginAttempts.MustRender(w, r, loginAttempt, company)
}

func collectLoginAttemptEntries(ctx context.Context, conn *database.Conn) (loginAttemptIndex, error) {
	rows, err := conn.Query(ctx, `
		select user_name
		     , host(ip_address)
		     , attempted_at
		     , success
		from company_login_attempt
		order by attempted_at desc
		limit 500
	`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var entries loginAttemptIndex
	for rows.Next() {
		entry := &loginAttemptEntry{}
		if err = rows.Scan(&entry.UserName, &entry.IPAddress, &entry.Date, &entry.Success); err != nil {
			return nil, err
		}
		entries = append(entries, entry)
	}

	return entries, nil
}

type loginAttemptEntry struct {
	UserName  string
	IPAddress string
	Date      time.Time
	Success   bool
}

type loginAttemptIndex []*loginAttemptEntry

func (page *loginAttemptIndex) MustRender(w http.ResponseWriter, r *http.Request, loginAttempt *auth.User, company *auth.Company) {
	template.MustRenderAdmin(w, r, loginAttempt, company, "user/login-attempts.gohtml", page)
}
