package controller

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

	"github.com/gofiber/fiber/v2"

	utilRes "jaecoo-be/utils/response"
)

type galleryFilesController struct {
	galleryFilesService service.GalleryFilesService
}

type GalleryFilesController 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 NewGalleryFilesController(galleryFilesService service.GalleryFilesService) GalleryFilesController {
	return &galleryFilesController{
		galleryFilesService: galleryFilesService,
	}
}

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

	reqContext := request.GalleryFilesQueryRequestContext{
		GalleryID: c.Query("gallery_id"),
		Title:     c.Query("title"),
	}
	req := reqContext.ToParamRequest()
	req.Pagination = paginate

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

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

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

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

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

// Save GalleryFile
// @Summary      Create GalleryFile
// @Description  API for creating GalleryFile with file upload
// @Tags         GalleryFiles
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param        file formData file false "Upload file"
// @Param        gallery_id formData int true "Gallery ID"
// @Param        title formData string false "Gallery file title"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /gallery-files [post]
func (_i *galleryFilesController) 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
	galleryIDStr := c.FormValue("gallery_id")
	galleryID, err := strconv.ParseUint(galleryIDStr, 10, 0)
	if err != nil {
		return utilRes.Resp(c, utilRes.Response{
			Success:  false,
			Messages: utilRes.Messages{"Invalid gallery_id"},
		})
	}

	req := request.GalleryFilesCreateRequest{
		GalleryID: uint(galleryID),
	}

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

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

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

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

// Update GalleryFile
// @Summary      Update GalleryFile
// @Description  API for updating GalleryFile with file upload
// @Tags         GalleryFiles
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param        id path int true "GalleryFile ID"
// @Param        file formData file false "Upload file"
// @Param        gallery_id formData int false "Gallery ID"
// @Param        title formData string false "Gallery file title"
// @Param        is_active formData bool false "Is active"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /gallery-files/{id} [put]
func (_i *galleryFilesController) 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"},
		})
	}

	req := request.GalleryFilesUpdateRequest{}

	// Extract gallery_id if provided
	if galleryIDStr := c.FormValue("gallery_id"); galleryIDStr != "" {
		galleryID, err := strconv.ParseUint(galleryIDStr, 10, 0)
		if err != nil {
			return utilRes.Resp(c, utilRes.Response{
				Success:  false,
				Messages: utilRes.Messages{"Invalid gallery_id"},
			})
		}
		galleryIDUint := uint(galleryID)
		req.GalleryID = &galleryIDUint
	}

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

	// Extract is_active if provided
	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.galleryFilesService.Update(c, uint(id), req)
	if err != nil {
		return err
	}

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

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

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

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

// Viewer GalleryFile
// @Summary      Viewer GalleryFile
// @Description  API for viewing GalleryFile file
// @Tags         GalleryFiles
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param        filename path string true "Gallery 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       /gallery-files/viewer/{filename} [get]
func (_i *galleryFilesController) Viewer(c *fiber.Ctx) error {
	return _i.galleryFilesService.Viewer(c)
}
