package controller

import (
	"netidhub-saas-be/app/middleware"
	"netidhub-saas-be/app/module/schedules/request"
	"netidhub-saas-be/app/module/schedules/service"
	"netidhub-saas-be/utils/paginator"
	"strconv"

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

	utilRes "netidhub-saas-be/utils/response"
	utilVal "netidhub-saas-be/utils/validator"
)

type schedulesController struct {
	schedulesService service.SchedulesService
	Log              zerolog.Logger
}

type SchedulesController 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
}

func NewSchedulesController(schedulesService service.SchedulesService, log zerolog.Logger) SchedulesController {
	return &schedulesController{
		schedulesService: schedulesService,
		Log:              log,
	}
}

// All Schedules
// @Summary      Get all Schedules
// @Description  API for getting all Schedules
// @Tags         Schedules
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param        Authorization header string false "Insert your access token" default(Bearer <Add access token here>)
// @Param 	     req query request.SchedulesQueryRequest 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       /schedules [get]
func (_i *schedulesController) All(c *fiber.Ctx) error {
	paginate, err := paginator.Paginate(c)
	if err != nil {
		return err
	}

	reqContext := request.SchedulesQueryRequestContext{
		Title:           c.Query("title"),
		Description:     c.Query("description"),
		Location:        c.Query("location"),
		TypeId:          c.Query("typeId"),
		StartDate:       c.Query("startDate"),
		EndDate:         c.Query("endDate"),
		IsLiveStreaming: c.Query("isLiveStreaming"),
		Speakers:        c.Query("speakers"),
		StatusId:        c.Query("statusId"),
		CreatedById:     c.Query("createdById"),
	}
	req := reqContext.ToParamRequest()
	req.Pagination = paginate

	// Get ClientId from context
	clientId := middleware.GetClientID(c)

	// Get Authorization token from header
	authToken := c.Get("Authorization")
	_i.Log.Info().Interface("clientId", clientId).Msg("")
	_i.Log.Info().Str("authToken", authToken).Msg("")

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

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

// Show Schedule
// @Summary      Get one Schedule
// @Description  API for getting one Schedule
// @Tags         Schedules
// @Security     Bearer
// @Param        id path int true "Schedule ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /schedules/{id} [get]
func (_i *schedulesController) Show(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	// Get ClientId from context
	clientId := middleware.GetClientID(c)

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

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

// Save Schedule
// @Summary      Create Schedule
// @Description  API for create Schedule
// @Tags         Schedules
// @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.SchedulesCreateRequest true "Required payload"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /schedules [post]
func (_i *schedulesController) Save(c *fiber.Ctx) error {
	req := new(request.SchedulesCreateRequest)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	authToken := c.Get("Authorization")

	// Get ClientId from context
	clientId := middleware.GetClientID(c)

	_i.Log.Info().Interface("clientId", clientId).Msg("")
	_i.Log.Info().Interface("authToken", authToken).Msg("")

	dataResult, err := _i.schedulesService.Save(clientId, *req)
	if err != nil {
		return err
	}

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

// Update Schedule
// @Summary      Update Schedule
// @Description  API for update Schedule
// @Tags         Schedules
// @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.SchedulesUpdateRequest true "Required payload"
// @Param        id path int true "Schedule ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /schedules/{id} [put]
func (_i *schedulesController) Update(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

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

	// Get ClientId from context
	clientId := middleware.GetClientID(c)

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

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

// Delete Schedule
// @Summary      Delete Schedule
// @Description  API for delete Schedule
// @Tags         Schedules
// @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 "Schedule ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /schedules/{id} [delete]
func (_i *schedulesController) Delete(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	// Get ClientId from context
	clientId := middleware.GetClientID(c)

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

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