package handlers

import (
	"net/http"

	"go-server/internal/service"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

type AdminController struct {
	service *service.UserService
}

func NewAdminController(service *service.UserService) *AdminController {
	return &AdminController{service}
}

func (uc *AdminController) GetUserByID(c *gin.Context) {
	id := uuid.MustParse(c.Param("id"))
	user, err := uc.service.GetByID(c, id)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
		return
	}

	c.JSON(http.StatusOK, user)
}

func (uc *AdminController) GetUsers(c *gin.Context) {
	users, err := uc.service.GetAll(c)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, users)
}

func (uc *AdminController) CreateUser(c *gin.Context) {
	var input service.CreateUserInput
	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
		return
	}

	user, err := uc.service.Create(c, input)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, user)
}

func (uc *AdminController) DeleteUser(c *gin.Context) {
	id := uuid.MustParse(c.Param("id"))
	err := uc.service.Delete(c, id)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "User deleted successfully"})
}

func (uc *AdminController) ChangePassword(c *gin.Context) {
	id := uuid.MustParse(c.Param("id"))
	var input service.ChangePasswordInput
	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
		return
	}
	err := uc.service.ChangePassword(c, id, input)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "Password changed successfully"})
}
