// internal/controllers/auth_controller.go
package controllers

import (
	"lost-and-found/internal/services"
	"lost-and-found/internal/utils"
	"net/http"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

type AuthController struct {
	authService *services.AuthService
}

func NewAuthController(db *gorm.DB, logger *zap.Logger) *AuthController {
	return &AuthController{
		authService: services.NewAuthService(db, logger),
	}
}

// Register handles user registration
// POST /api/register
func (c *AuthController) Register(ctx *gin.Context) {
	var req services.RegisterRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		utils.ErrorResponse(ctx, http.StatusBadRequest, "Invalid request data", err.Error())
		return
	}

	// Get IP and User-Agent
	ipAddress := ctx.ClientIP()
	userAgent := ctx.Request.UserAgent()

	// Register user
	result, err := c.authService.Register(req, ipAddress, userAgent)
	if err != nil {
		utils.ErrorResponse(ctx, http.StatusBadRequest, "Registration failed", err.Error())
		return
	}

	utils.SuccessResponse(ctx, http.StatusCreated, "Registration successful", result)
}

// Login handles user login
// POST /api/login
func (c *AuthController) Login(ctx *gin.Context) {
	var req services.LoginRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		utils.ErrorResponse(ctx, http.StatusBadRequest, "Invalid request data", err.Error())
		return
	}

	// Get IP and User-Agent
	ipAddress := ctx.ClientIP()
	userAgent := ctx.Request.UserAgent()

	// Login user
	result, err := c.authService.Login(req, ipAddress, userAgent)
	if err != nil {
		utils.ErrorResponse(ctx, http.StatusUnauthorized, "Login failed", err.Error())
		return
	}

	utils.SuccessResponse(ctx, http.StatusOK, "Login successful", result)
}

// RefreshToken handles token refresh
// POST /api/refresh-token
func (c *AuthController) RefreshToken(ctx *gin.Context) {
	var req struct {
		Token string `json:"token" binding:"required"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		utils.ErrorResponse(ctx, http.StatusBadRequest, "Invalid request data", err.Error())
		return
	}

	// Refresh token
	newToken, err := c.authService.RefreshToken(req.Token)
	if err != nil {
		utils.ErrorResponse(ctx, http.StatusUnauthorized, "Token refresh failed", err.Error())
		return
	}

	utils.SuccessResponse(ctx, http.StatusOK, "Token refreshed", gin.H{
		"token": newToken,
	})
}

// GetMe returns current user info
// GET /api/me
func (c *AuthController) GetMe(ctx *gin.Context) {
	user, exists := ctx.Get("user")
	if !exists {
		utils.ErrorResponse(ctx, http.StatusUnauthorized, "User not found", "")
		return
	}

	utils.SuccessResponse(ctx, http.StatusOK, "User info retrieved", user)
}