package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"

	"main/db"
	"main/handler"
	"net/http"
	"regexp"
	"time"

	"github.com/golang-jwt/jwt/v4"
	"github.com/gorilla/mux"
	"github.com/rs/cors"
	"go.mongodb.org/mongo-driver/bson"
	"golang.org/x/crypto/bcrypt"
)

var jwtKey = []byte("mysecret123")

type User struct {
	ID       string `json:"id,omitempty"`
	Username string `json:"username"`
	Email    string `json:"email"`
	Password string `json:"password,omitempty"`
}

type Claims struct {
	Username string `json:"username"`
	jwt.RegisteredClaims
}

func isValidEmail(email string) error {
	const emailRegex = `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
	re := regexp.MustCompile(emailRegex)
	if !re.MatchString(email) {
		return errors.New("invalid email format")
	}
	return nil
}

func registerHnadler(w http.ResponseWriter, r *http.Request) {
	var user User
	_ = json.NewDecoder(r.Body).Decode(&user)
	w.Header().Set("Content-Type", "application/json")
	fmt.Print(user)
	if user.Email == "" || user.Username == "" || user.Password == "" {
		http.Error(w, `{"message": "please fill required fileds"}`, http.StatusBadRequest)
		return
	}

	if err := isValidEmail(user.Email); err != nil {
		http.Error(w, `{"message": "Email format is not correct"}`, http.StatusBadRequest)
		return
	}

	var existUser User
	_ = db.UserCollection.FindOne(context.TODO(), bson.M{"email": user.Email}).Decode(&existUser)

	if existUser.Email == user.Email {
		http.Error(w, `{"message": "User already registered"}`, http.StatusUnauthorized)
		return
	}

	hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
	user.Password = string(hashedPassword)

	_, err := db.UserCollection.InsertOne(context.TODO(), user)
	if err != nil {
		http.Error(w, `{"message": "Could not create user"}`, http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode("User registerd successfully")
}

func loginHandler(w http.ResponseWriter, r *http.Request) {
	var creds User
	_ = json.NewDecoder(r.Body).Decode(&creds)

	var storedUser User
	err := db.UserCollection.FindOne(context.TODO(), bson.M{"username": creds.Username}).Decode(&storedUser)
	if err != nil {
		http.Error(w, `{"message": "Invalid username or password"}`, http.StatusUnauthorized)
		return
	}

	err = bcrypt.CompareHashAndPassword([]byte(storedUser.Password), []byte(creds.Password))
	if err != nil {
		http.Error(w, `{"message":  "Invalid username or password"}`, http.StatusUnauthorized)
		return
	}

	expirationTime := time.Now().Add(15 * time.Minute)
	claims := &Claims{
		Username: creds.Username,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(expirationTime),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(jwtKey)
	if err != nil {
		// Debugging: Log the error
		fmt.Printf("Error generating token: %v\n", err)
		http.Error(w, "Error generating token", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]string{
		"token": tokenString,
	})
}

func main() {

	db.InitDB()
	router := mux.NewRouter()

	router.HandleFunc("/register", registerHnadler)
	router.HandleFunc("/login", loginHandler)
	router.HandleFunc("/createcluster", handler.CreateClusterHandler)
	//handler.RegsiterClusterRoute(router)
	// Enable CORS
	c := cors.New(cors.Options{
		AllowedOrigins:   []string{"*"}, // Allow all origins
		AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowedHeaders:   []string{"Content-Type", "Authorization", "X-Requested-With", "Accept", "Origin"},
		ExposedHeaders:   []string{"Content-Length"},
		AllowCredentials: true,
		Debug:            true, // Enable debug logging
	})

	http.ListenAndServe("0.0.0.0:8082", c.Handler(router))
}
