package controller

import (
	"jaecoo-be/app/module/banners/request"
	"jaecoo-be/app/module/banners/service"
	"jaecoo-be/utils/paginator"
	"strconv"

	"github.com/gofiber/fiber/v2"

	utilRes "jaecoo-be/utils/response"
)

type bannersController struct {
	bannersService service.BannersService
}

type BannersController 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
	Viewer(c *fiber.Ctx) error
}

func NewBannersController(bannersService service.BannersService) BannersController {
	return &bannersController{
		bannersService: bannersService,
	}
}

// All Banners
// @Summary      Get all Banners
// @Description  API for getting all Banners
// @Tags         Banners
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param 	     req query request.BannersQueryRequestContext 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       /banners [get]
func (_i *bannersController) All(c *fiber.Ctx) error {
	paginate, err := paginator.Paginate(c)
	if err != nil {
		return err
	}

	reqContext := request.BannersQueryRequestContext{
		Title:    c.Query("title"),
		Position: c.Query("position"),
		Status:   c.Query("status"),
	}
	req := reqContext.ToParamRequest()
	req.Pagination = paginate

	bannersData, paging, err := _i.bannersService.GetAll(req)
	if err != nil {
		return err
	}

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

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

	bannerData, err := _i.bannersService.GetOne(uint(id))
	if err != nil {
		return err
	}

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

// Save Banner
// @Summary      Create Banner
// @Description  API for creating Banner with file upload
// @Tags         Banners
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param        file formData file false "Upload file"
// @Param        title formData string true "Banner title"
// @Param        description formData string false "Banner description"
// @Param        position formData string false "Banner position"
// @Param        status formData string false "Banner status"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /banners [post]
func (_i *bannersController) Save(c *fiber.Ctx) error {
	// Parse multipart form
	form, err := c.MultipartForm()
	if err != nil {
		return utilRes.Resp(c, utilRes.Response{
			Success:  false,
			Messages: utilRes.Messages{"Failed to parse form data"},
		})
	}

	// Extract form values
	req := request.BannersCreateRequest{
		Title: c.FormValue("title"),
	}

	if description := c.FormValue("description"); description != "" {
		req.Description = &description
	}

	if position := c.FormValue("position"); position != "" {
		req.Position = &position
	}

	if status := c.FormValue("status"); status != "" {
		req.Status = &status
	}

	// Validate required fields
	if req.Title == "" {
		return utilRes.Resp(c, utilRes.Response{
			Success:  false,
			Messages: utilRes.Messages{"Title is required"},
		})
	}

	// Check if file is uploaded
	if len(form.File["file"]) > 0 {
		// File will be handled in service
	}

	dataResult, err := _i.bannersService.Create(c, req)
	if err != nil {
		return err
	}

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

// Update Banner
// @Summary      Update Banner
// @Description  API for updating Banner with file upload
// @Tags         Banners
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param        id path int true "Banner ID"
// @Param        file formData file false "Upload file"
// @Param        title formData string false "Banner title"
// @Param        description formData string false "Banner description"
// @Param        position formData string false "Banner position"
// @Param        status formData string false "Banner status"
// @Param        is_active formData bool false "Banner is_active"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /banners/{id} [put]
func (_i *bannersController) Update(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	// Parse multipart form
	form, err := c.MultipartForm()
	if err != nil {
		return utilRes.Resp(c, utilRes.Response{
			Success:  false,
			Messages: utilRes.Messages{"Failed to parse form data"},
		})
	}

	// Extract form values
	req := request.BannersUpdateRequest{}

	if title := c.FormValue("title"); title != "" {
		req.Title = &title
	}

	if description := c.FormValue("description"); description != "" {
		req.Description = &description
	}

	if position := c.FormValue("position"); position != "" {
		req.Position = &position
	}

	if status := c.FormValue("status"); status != "" {
		req.Status = &status
	}

	if isActiveStr := c.FormValue("is_active"); isActiveStr != "" {
		isActive := isActiveStr == "true" || isActiveStr == "1"
		req.IsActive = &isActive
	}

	// Check if file is uploaded
	if len(form.File["file"]) > 0 {
		// File will be handled in service
	}

	dataResult, err := _i.bannersService.Update(c, uint(id), req)
	if err != nil {
		return err
	}

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

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

	err = _i.bannersService.Delete(uint(id))
	if err != nil {
		return err
	}

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

// Viewer Banner
// @Summary      Viewer Banner
// @Description  API for viewing Banner file
// @Tags         Banners
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param        filename path string true "Banner File Name (e.g., user_277788.png)"
// @Success      200  {file}  file
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /banners/viewer/{filename} [get]
func (_i *bannersController) Viewer(c *fiber.Ctx) error {
	return _i.bannersService.Viewer(c)
}
