package api

import (
	"errors"
	"net/http"
	"time"

	"github.com/jackc/pgerrcode"
	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
	"golang.org/x/crypto/bcrypt"

	"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
	"git.fabledsword.com/bvandeusen/minstrel/internal/audit"
	"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
	"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)

type adminUserView struct {
	ID                  string  `json:"id"`
	Username            string  `json:"username"`
	DisplayName         *string `json:"display_name"`
	IsAdmin             bool    `json:"is_admin"`
	AutoApproveRequests bool    `json:"auto_approve_requests"`
	DebugModeEnabled    bool    `json:"debug_mode_enabled"`
	CreatedAt           string  `json:"created_at"`
}

type listUsersResp struct {
	Users []adminUserView `json:"users"`
}

func (h *handlers) handleAdminListUsers(w http.ResponseWriter, r *http.Request) {
	q := dbq.New(h.pool)
	rows, err := q.ListUsers(r.Context())
	if err != nil {
		writeErrWithLog(w, h.logger, "admin: list users failed", apierror.Internal(err))
		return
	}
	out := make([]adminUserView, 0, len(rows))
	for _, row := range rows {
		v := adminUserView{
			ID:                  uuidToString(row.ID),
			Username:            row.Username,
			DisplayName:         row.DisplayName,
			IsAdmin:             row.IsAdmin,
			AutoApproveRequests: row.AutoApproveRequests,
			DebugModeEnabled:    row.DebugModeEnabled,
			CreatedAt:           row.CreatedAt.Time.UTC().Format(time.RFC3339),
		}
		out = append(out, v)
	}
	writeJSON(w, http.StatusOK, listUsersResp{Users: out})
}

type updateUserAdminReq struct {
	IsAdmin bool `json:"is_admin"`
}

func (h *handlers) handleUpdateUserAdmin(w http.ResponseWriter, r *http.Request) {
	caller, ok := requireUser(w, r)
	if !ok {
		return
	}
	targetID, ok := requireURLUUID(w, r, "id")
	if !ok {
		return
	}
	var req updateUserAdminReq
	if !decodeBody(w, r, &req) {
		return
	}

	q := dbq.New(h.pool)

	// Last-admin guard: if demoting (is_admin=false) AND target is
	// currently the only admin, refuse. The check has a race window
	// (between counting and updating, another admin could be demoted)
	// but the worst-case outcome is "no admins left," which the
	// operator can recover from via the env-driven bootstrap or the
	// CLI password-reset path. The check still prevents the common
	// path of "admin demotes themselves and loses access."
	if !req.IsAdmin {
		count, err := q.CountAdmins(r.Context())
		if err != nil {
			writeErrWithLog(w, h.logger, "admin: count admins failed", apierror.Internal(err))
			return
		}
		// We need to know whether the target is currently an admin.
		// If they're already not-admin, the demote is a no-op (we
		// allow it). If they ARE admin and they're the last one, refuse.
		current, err := q.GetUserByID(r.Context(), targetID)
		if err != nil {
			writeErrWithLog(w, h.logger, "admin: get user failed", apierror.Internal(err))
			return
		}
		if current.IsAdmin && count <= 1 {
			writeErr(w, apierror.Conflict("last_admin",
				"can't remove the last admin — promote someone else first"))
			return
		}
	}

	updated, err := q.UpdateUserAdmin(r.Context(), dbq.UpdateUserAdminParams{
		ID:      targetID,
		IsAdmin: req.IsAdmin,
	})
	if err != nil {
		writeErrWithLog(w, h.logger, "admin: update user admin failed", apierror.Internal(err))
		return
	}

	action := audit.ActionPromoteAdmin
	if !req.IsAdmin {
		action = audit.ActionDemoteAdmin
	}
	audit.WriteOrLog(r.Context(), h.pool, h.logger, caller.ID, targetID, action, nil)

	writeJSON(w, http.StatusOK, adminUserView{
		ID:                  uuidToString(updated.ID),
		Username:            updated.Username,
		DisplayName:         updated.DisplayName,
		IsAdmin:             updated.IsAdmin,
		AutoApproveRequests: updated.AutoApproveRequests,
		DebugModeEnabled:    updated.DebugModeEnabled,
		CreatedAt:           updated.CreatedAt.Time.UTC().Format(time.RFC3339),
	})
}

// --- Admin user create -----------------------------------------------------

type adminCreateUserReq struct {
	Username    string  `json:"username"`
	Password    string  `json:"password"`
	DisplayName *string `json:"display_name"`
	IsAdmin     bool    `json:"is_admin"`
}

func (h *handlers) handleAdminCreateUser(w http.ResponseWriter, r *http.Request) {
	caller, ok := requireUser(w, r)
	if !ok {
		return
	}
	var req adminCreateUserReq
	if !decodeBody(w, r, &req) {
		return
	}
	if !usernameRe.MatchString(req.Username) {
		writeErr(w, apierror.BadRequest("username_invalid", "username must be 3-32 chars, alphanumeric + underscore + hyphen"))
		return
	}
	if len(req.Password) < minPasswordLength {
		writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars"))
		return
	}

	hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
	if err != nil {
		writeErrWithLog(w, h.logger, "admin create user: hash failed", apierror.Internal(err))
		return
	}
	apiToken, err := auth.MintSessionToken()
	if err != nil {
		writeErrWithLog(w, h.logger, "admin create user: mint token failed", apierror.Internal(err))
		return
	}

	q := dbq.New(h.pool)
	user, err := q.CreateUserAdmin(r.Context(), dbq.CreateUserAdminParams{
		Username:     req.Username,
		PasswordHash: string(hash),
		ApiToken:     apiToken,
		IsAdmin:      req.IsAdmin,
		DisplayName:  req.DisplayName,
	})
	if err != nil {
		var pgErr *pgconn.PgError
		if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation {
			writeErr(w, apierror.Conflict("username_taken", ""))
			return
		}
		writeErrWithLog(w, h.logger, "admin create user: insert failed", apierror.Internal(err))
		return
	}

	audit.WriteOrLog(r.Context(), h.pool, h.logger, caller.ID, user.ID, audit.ActionCreateUserAdmin,
		map[string]any{"is_admin": req.IsAdmin})

	writeJSON(w, http.StatusOK, adminUserView{
		ID:                  uuidToString(user.ID),
		Username:            user.Username,
		DisplayName:         user.DisplayName,
		IsAdmin:             user.IsAdmin,
		AutoApproveRequests: user.AutoApproveRequests,
		DebugModeEnabled:    user.DebugModeEnabled,
		CreatedAt:           user.CreatedAt.Time.UTC().Format(time.RFC3339),
	})
}

// --- Admin user delete -----------------------------------------------------

func (h *handlers) handleAdminDeleteUser(w http.ResponseWriter, r *http.Request) {
	caller, ok := requireUser(w, r)
	if !ok {
		return
	}

	q := dbq.New(h.pool)
	target, apiErr := resolveByID(r, "id", q.GetUserByID, "user")
	if apiErr != nil {
		writeErr(w, apiErr)
		return
	}

	// Last-admin guard: refuse delete if target is the only admin.
	if target.IsAdmin {
		count, cerr := q.CountAdmins(r.Context())
		if cerr != nil {
			writeErrWithLog(w, h.logger, "admin delete user: count admins failed", apierror.Internal(cerr))
			return
		}
		if count <= 1 {
			writeErr(w, apierror.Conflict("last_admin",
				"can't delete the last admin — promote someone else first"))
			return
		}
	}

	if err := q.DeleteUser(r.Context(), target.ID); err != nil {
		writeErrWithLog(w, h.logger, "admin delete user: delete failed", apierror.Internal(err))
		return
	}

	audit.WriteOrLog(r.Context(), h.pool, h.logger, caller.ID, target.ID, audit.ActionDeleteUser,
		map[string]any{"username": target.Username, "was_admin": target.IsAdmin})

	w.WriteHeader(http.StatusNoContent)
}

// --- Admin password reset --------------------------------------------------

type adminResetPasswordReq struct {
	Password string `json:"password"`
}

func (h *handlers) handleAdminResetPassword(w http.ResponseWriter, r *http.Request) {
	caller, ok := requireUser(w, r)
	if !ok {
		return
	}
	targetID, ok := requireURLUUID(w, r, "id")
	if !ok {
		return
	}
	var req adminResetPasswordReq
	if !decodeBody(w, r, &req) {
		return
	}
	if len(req.Password) < minPasswordLength {
		writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars"))
		return
	}

	q := dbq.New(h.pool)
	// Verify target exists for a useful 404.
	if _, err := q.GetUserByID(r.Context(), targetID); err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: ""})
			return
		}
		writeErrWithLog(w, h.logger, "admin reset password: lookup failed", apierror.Internal(err))
		return
	}

	hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
	if err != nil {
		writeErrWithLog(w, h.logger, "admin reset password: hash failed", apierror.Internal(err))
		return
	}
	if err := q.ResetUserPassword(r.Context(), dbq.ResetUserPasswordParams{
		ID:           targetID,
		PasswordHash: string(hash),
	}); err != nil {
		writeErrWithLog(w, h.logger, "admin reset password: update failed", apierror.Internal(err))
		return
	}

	audit.WriteOrLog(r.Context(), h.pool, h.logger, caller.ID, targetID, audit.ActionPasswordResetAdmin, nil)

	w.WriteHeader(http.StatusNoContent)
}

// --- Admin auto-approve toggle ---------------------------------------------

type adminAutoApproveReq struct {
	AutoApprove bool `json:"auto_approve"`
}

func (h *handlers) handleAdminAutoApproveToggle(w http.ResponseWriter, r *http.Request) {
	caller, ok := requireUser(w, r)
	if !ok {
		return
	}
	targetID, ok := requireURLUUID(w, r, "id")
	if !ok {
		return
	}
	var req adminAutoApproveReq
	if !decodeBody(w, r, &req) {
		return
	}

	q := dbq.New(h.pool)
	updated, err := q.UpdateUserAutoApprove(r.Context(), dbq.UpdateUserAutoApproveParams{
		ID:                  targetID,
		AutoApproveRequests: req.AutoApprove,
	})
	if err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: ""})
			return
		}
		writeErrWithLog(w, h.logger, "admin auto-approve: update failed", apierror.Internal(err))
		return
	}

	audit.WriteOrLog(r.Context(), h.pool, h.logger, caller.ID, targetID, audit.ActionAutoApproveToggle,
		map[string]any{"auto_approve": req.AutoApprove})

	writeJSON(w, http.StatusOK, adminUserView{
		ID:                  uuidToString(updated.ID),
		Username:            updated.Username,
		DisplayName:         updated.DisplayName,
		IsAdmin:             updated.IsAdmin,
		AutoApproveRequests: updated.AutoApproveRequests,
		DebugModeEnabled:    updated.DebugModeEnabled,
		CreatedAt:           updated.CreatedAt.Time.UTC().Format(time.RFC3339),
	})
}
