package controller

import (
	"strconv"

	"gitlab.com/mbugroup/lti-api.git/internal/modules/finance/initials/dto"
	service "gitlab.com/mbugroup/lti-api.git/internal/modules/finance/initials/services"
	validation "gitlab.com/mbugroup/lti-api.git/internal/modules/finance/initials/validations"
	"gitlab.com/mbugroup/lti-api.git/internal/response"

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

type InitialController struct {
	InitialService service.InitialService
}

func NewInitialController(initialService service.InitialService) *InitialController {
	return &InitialController{
		InitialService: initialService,
	}
}

func (u *InitialController) GetOne(c *fiber.Ctx) error {
	param := c.Params("id")

	id, err := strconv.Atoi(param)
	if err != nil {
		return fiber.NewError(fiber.StatusBadRequest, "Invalid Id")
	}

	result, err := u.InitialService.GetOne(c, uint(id))
	if err != nil {
		return err
	}

	return c.Status(fiber.StatusOK).
		JSON(response.Success{
			Code:    fiber.StatusOK,
			Status:  "success",
			Message: "Get initial successfully",
			Data:    dto.ToInitialListDTO(*result),
		})
}

func (u *InitialController) CreateOne(c *fiber.Ctx) error {
	req := new(validation.Create)

	if err := c.BodyParser(req); err != nil {
		return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
	}

	result, err := u.InitialService.CreateOne(c, req)
	if err != nil {
		return err
	}

	return c.Status(fiber.StatusCreated).
		JSON(response.Success{
			Code:    fiber.StatusCreated,
			Status:  "success",
			Message: "Create initial successfully",
			Data:    dto.ToInitialListDTO(*result),
		})
}

func (u *InitialController) UpdateOne(c *fiber.Ctx) error {
	req := new(validation.Update)
	param := c.Params("id")

	id, err := strconv.Atoi(param)
	if err != nil {
		return fiber.NewError(fiber.StatusBadRequest, "Invalid Id")
	}

	if err := c.BodyParser(req); err != nil {
		return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
	}

	result, err := u.InitialService.UpdateOne(c, req, uint(id))
	if err != nil {
		return err
	}

	return c.Status(fiber.StatusOK).
		JSON(response.Success{
			Code:    fiber.StatusOK,
			Status:  "success",
			Message: "Update initial successfully",
			Data:    dto.ToInitialListDTO(*result),
		})
}
