package utm

import (
	"gitea.pena/SQuiz/common/dal"
	"github.com/gofiber/fiber/v2"
)

type Deps struct {
	DAL *dal.DAL
}

type UTM struct {
	dal *dal.DAL
}

func NewUTMController(deps Deps) *UTM {
	return &UTM{
		dal: deps.DAL,
	}
}

func (r *UTM) CreateQuizUTM(ctx *fiber.Ctx) error {
	var req struct {
		QuizID int64  `json:"quiz_id"`
		UTM    string `json:"utm"`
	}

	if err := ctx.BodyParser(&req); err != nil {
		return ctx.Status(fiber.StatusBadRequest).SendString(err.Error())
	}

	if req.QuizID <= 0 || req.UTM == "" {
		return ctx.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "quiz_id and utm are required"})
	}

	utm, err := r.dal.QuizRepo.CreateQuizUTM(ctx.Context(), req.QuizID, req.UTM)
	if err != nil {
		return ctx.Status(fiber.StatusInternalServerError).SendString(err.Error())
	}

	return ctx.Status(fiber.StatusOK).JSON(utm)
}

func (r *UTM) GetAllQuizUtms(ctx *fiber.Ctx) error {
	quizID, err := ctx.ParamsInt("quizID")
	if err != nil || quizID <= 0 {
		return ctx.Status(fiber.StatusBadRequest).SendString(err.Error())
	}

	utms, err := r.dal.QuizRepo.GetAllQuizUtms(ctx.Context(), int64(quizID))
	if err != nil {
		return ctx.Status(fiber.StatusInternalServerError).SendString(err.Error())
	}

	return ctx.JSON(utms)
}

func (r *UTM) DeleteQuizUTM(ctx *fiber.Ctx) error {
	utmID, err := ctx.ParamsInt("utmID")
	if err != nil || utmID <= 0 {
		return ctx.Status(fiber.StatusBadRequest).SendString(err.Error())
	}

	err = r.dal.QuizRepo.DeleteQuizUTM(ctx.Context(), int64(utmID))
	if err != nil {
		return ctx.Status(fiber.StatusInternalServerError).SendString(err.Error())
	}

	return ctx.SendStatus(fiber.StatusOK)
}
