package main

import (
	"fmt"
	"net/http"
	"strings"
)

func updatePhoneNumberHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed)
		return
	}

	newPhoneNumber := r.FormValue("phone_number")
	if newPhoneNumber == "" {
		http.Error(w, "Phone number is required", http.StatusBadRequest)
		return
	}

	if !strings.HasPrefix(newPhoneNumber, "010-") || len(newPhoneNumber) != 13 {
		http.Error(w, "Invalid phone number format", http.StatusBadRequest)
		return
	}

	if err := updateConfigFile(newPhoneNumber); err != nil {
		http.Error(w, fmt.Sprintf("Failed to update config: %v", err), http.StatusInternalServerError)
		return
	}

	if err := loadConfig(); err != nil {
		http.Error(w, fmt.Sprintf("Failed to reload config: %v", err), http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "Phone number updated successfully to %s", newPhoneNumber)
}
