package auth

import (
	"context"
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"net/http"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/mrhid6/vantage/admin/internal/audit"
	"github.com/mrhid6/vantage/admin/internal/db"
	"github.com/mrhid6/vantage/admin/internal/mail"
	"github.com/mrhid6/vantage/admin/internal/models"
	"go.mongodb.org/mongo-driver/v2/bson"
	"golang.org/x/crypto/bcrypt"
)

// BcryptCost matches the control plane and sitesvc. Changing it here alone would
// make hashes inconsistent across services that may one day compare them.
const BcryptCost = 12

// VerifyWindow mirrors sitesvc's proven pattern: 32 random bytes, only the
// SHA-256 hash stored, 24-hour expiry.
const VerifyWindow = 24 * time.Hour

// CreateCustomerUser creates an unverified self-hosted customer login and emails
// the verification link. Called during purchase (spec 5) and by staff.
func CreateCustomerUser(ctx context.Context, accountID, email, password string) error {
	hash, err := bcrypt.GenerateFromPassword([]byte(password), BcryptCost)
	if err != nil {
		return err
	}

	raw := make([]byte, 32)
	if _, err := rand.Read(raw); err != nil {
		return err
	}
	token := hex.EncodeToString(raw)
	sum := sha256.Sum256([]byte(token))
	expiry := time.Now().UTC().Add(VerifyWindow)

	u := models.CustomerUser{
		UserID:            uuid.NewString(),
		AccountID:         accountID,
		Email:             strings.ToLower(strings.TrimSpace(email)),
		PasswordHash:      string(hash),
		VerifyTokenHash:   hex.EncodeToString(sum[:]),
		VerifyTokenExpiry: &expiry,
		CreatedAt:         time.Now().UTC(),
	}
	if _, err := db.Admin("customer_users").InsertOne(ctx, u); err != nil {
		return err
	}
	return mail.SendVerification(u.Email, token)
}

// HandleVerify consumes a verification token.
func HandleVerify(c *gin.Context) {
	token := c.Query("token")
	if token == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "missing token"})
		return
	}
	sum := sha256.Sum256([]byte(token))
	now := time.Now().UTC()

	res, err := db.Admin("customer_users").UpdateOne(c.Request.Context(),
		bson.M{
			"verify_token_hash":   hex.EncodeToString(sum[:]),
			"verify_token_expiry": bson.M{"$gt": now},
		},
		bson.M{
			"$set":   bson.M{"verified_at": now},
			"$unset": bson.M{"verify_token_hash": "", "verify_token_expiry": ""},
		})
	if err != nil || res.MatchedCount == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "that link is invalid or has expired"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"verified": true})
}

// HandleCustomerLogin authenticates a self-hosted customer.
func HandleCustomerLogin(c *gin.Context) {
	var body struct {
		Email    string `json:"email"`
		Password string `json:"password"`
	}
	if err := c.ShouldBindJSON(&body); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "email and password are required"})
		return
	}
	email := strings.ToLower(strings.TrimSpace(body.Email))
	ctx := c.Request.Context()

	if !allowAttempt(email, c.ClientIP()) {
		c.JSON(http.StatusTooManyRequests, gin.H{"error": "too many attempts, try again later"})
		return
	}

	reject := func(reason string) {
		audit.Write(ctx, models.AuditEntry{
			Actor: email, Action: "customer.login_failed", IP: c.ClientIP(), Detail: reason})
		c.JSON(http.StatusUnauthorized, gin.H{"error": genericAuthError})
	}

	var u models.CustomerUser
	if err := db.Admin("customer_users").FindOne(ctx, bson.M{"email": email}).Decode(&u); err != nil {
		bcrypt.CompareHashAndPassword([]byte(dummyHash), []byte(body.Password))
		reject("unknown email")
		return
	}
	if bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(body.Password)) != nil {
		reject("bad password")
		return
	}
	if u.VerifiedAt == nil {
		// Distinct from genericAuthError on purpose: the address is already
		// known to be theirs, so there is nothing to disclose, and "check your
		// email" is the only useful thing to say.
		c.JSON(http.StatusForbidden, gin.H{"error": "verify your email address first"})
		return
	}

	id, err := Save(ctx, Session{
		UserID: u.UserID, Kind: KindCustomer, Email: u.Email, AccountID: u.AccountID,
	})
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "session failed"})
		return
	}
	SetCookie(c, id)
	clearAttempts(email)
	audit.Write(ctx, models.AuditEntry{
		Actor: email, Action: "customer.login", AccountID: u.AccountID, IP: c.ClientIP()})
	c.JSON(http.StatusOK, gin.H{"kind": KindCustomer, "email": u.Email})
}
