package controller

import (
	"strconv"
	"strings"
	"web-qudo-be/app/middleware"
	"web-qudo-be/app/module/activity_logs/request"
	"web-qudo-be/app/module/activity_logs/service"
	"web-qudo-be/utils/paginator"
	utilRes "web-qudo-be/utils/response"
	utilVal "web-qudo-be/utils/validator"

	"github.com/gofiber/fiber/v2"
	"github.com/rs/zerolog"
)

type activityLogsController struct {
	activityLogsService service.ActivityLogsService
	Log                 zerolog.Logger
}

type ActivityLogsController interface {
	All(c *fiber.Ctx) error
	Show(c *fiber.Ctx) error
	Save(c *fiber.Ctx) error
	Update(c *fiber.Ctx) error
	Delete(c *fiber.Ctx) error
	GetActivityStats(c *fiber.Ctx) error
}

func NewActivityLogsController(activityLogsService service.ActivityLogsService, log zerolog.Logger) ActivityLogsController {
	return &activityLogsController{
		activityLogsService: activityLogsService,
		Log:                 log,
	}
}

// All get all ActivityLogs
// @Summary      Get all ActivityLogs
// @Description  API for getting all ActivityLogs
// @Tags         ActivityLogs
// @Security     Bearer
// @Param        X-Client-Key header string false "Insert the X-Client-Key"
// @Param 	     req query request.ActivityLogsQueryRequest false "query parameters"
// @Param 	     req query paginator.Pagination false "pagination parameters"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /activity-logs [get]
func (_i *activityLogsController) All(c *fiber.Ctx) error {
	paginate, err := paginator.Paginate(c)
	if err != nil {
		return err
	}

	clientId := middleware.GetClientID(c)

	reqContext := request.ActivityLogsQueryRequestContext{
		ActivityTypeId: c.Query("activityTypeId"),
		Url:            c.Query("url"),
		ArticleId:      c.Query("articleId"),
		UserId:         c.Query("userId"),
	}
	req := reqContext.ToParamRequest()
	req.Pagination = paginate

	activityLogsData, paging, err := _i.activityLogsService.All(clientId, req)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"ActivityLogs list successfully retrieved"},
		Data:     activityLogsData,
		Meta:     paging,
	})
}

// Show get one ActivityLogs
// @Summary      Get one ActivityLogs
// @Description  API for getting one ActivityLogs
// @Tags         ActivityLogs
// @Security     Bearer
// @Param        X-Client-Key header string false "Insert the X-Client-Key"
// @Param        id path int true "ActivityLogs ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /activity-logs/detail/{id} [get]
func (_i *activityLogsController) Show(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	clientId := middleware.GetClientID(c)

	activityLogsData, err := _i.activityLogsService.Show(clientId, uint(id))
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"ActivityLogs successfully retrieved"},
		Data:     activityLogsData,
	})
}

// Save create ActivityLogs
// @Summary      Create ActivityLogs
// @Description  API for create ActivityLogs
// @Tags         ActivityLogs
// @Security     Bearer
// @Param        X-Client-Key header string false "Insert the X-Client-Key"
// @Param        X-Csrf-Token header string false "Insert the X-Csrf-Token"
// @Param        Authorization header string false "Insert your access token" default(Bearer <Add access token here>)
// @Param 	     payload body request.ActivityLogsCreateRequest true "Required payload"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /activity-logs [post]
func (_i *activityLogsController) Save(c *fiber.Ctx) error {
	req := new(request.ActivityLogsCreateRequest)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	clientId := middleware.GetClientID(c)

	var authToken *string
	getTokenFromHeader := c.Get("Authorization")
	if getTokenFromHeader == "" {
		authToken = nil
	} else {
		authToken = &getTokenFromHeader
	}
	visitorIp := GetVisitorIP(c)
	req.VisitorIp = &visitorIp
	dataResult, err := _i.activityLogsService.Save(clientId, *req, authToken)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"ActivityLogs successfully created"},
		Data:     dataResult,
	})
}

// Update update ActivityLogs
// @Summary      update ActivityLogs
// @Description  API for update ActivityLogs
// @Tags         ActivityLogs
// @Security     Bearer
// @Param        X-Client-Key header string false "Insert the X-Client-Key"
// @Param        X-Csrf-Token header string false "Insert the X-Csrf-Token"
// @Param 	     payload body request.ActivityLogsUpdateRequest true "Required payload"
// @Param        id path int true "ActivityLogs ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /activity-logs/{id} [put]
func (_i *activityLogsController) Update(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	req := new(request.ActivityLogsUpdateRequest)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	clientId := middleware.GetClientID(c)

	err = _i.activityLogsService.Update(clientId, uint(id), *req)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"ActivityLogs successfully updated"},
	})
}

// Delete delete ActivityLogs
// @Summary      delete ActivityLogs
// @Description  API for delete ActivityLogs
// @Tags         ActivityLogs
// @Security     Bearer
// @Param        X-Client-Key header string false "Insert the X-Client-Key"
// @Param        X-Csrf-Token header string false "Insert the X-Csrf-Token"
// @Param        id path int true "ActivityLogs ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /activity-logs/{id} [delete]
func (_i *activityLogsController) Delete(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	clientId := middleware.GetClientID(c)

	err = _i.activityLogsService.Delete(clientId, uint(id))
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"ActivityLogs successfully deleted"},
	})
}

// GetActivityStats get activity stats ActivityLogs
// @Summary      Get activity stats ActivityLogs
// @Description  API for get activity stats ActivityLogs
// @Tags         ActivityLogs
// @Security     Bearer
// @Param        X-Client-Key header string false "Insert the X-Client-Key"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /activity-logs/statistics [get]
func (_i *activityLogsController) GetActivityStats(c *fiber.Ctx) error {
	_i.Log.Info().Interface("GetActivityStats", "checker controller").Msg("")

	clientId := middleware.GetClientID(c)

	activityStatsData, err := _i.activityLogsService.GetActivityStats(clientId)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"ActivityLogs Stats successfully retrieved"},
		Data:     activityStatsData,
	})
}

func GetVisitorIP(c *fiber.Ctx) string {
	ip := c.Get("X-Forwarded-For")
	if ip == "" {
		ip = c.IP()
	}
	if strings.Contains(ip, ":") {
		ip = strings.Split(ip, ":")[0]
	}
	return ip
}
