package controller

import (
	"strconv"
	"strings"

	"github.com/gofiber/fiber/v2"

	"web-qudo-be/app/middleware"
	"web-qudo-be/app/module/media_library/request"
	"web-qudo-be/app/module/media_library/service"
	"web-qudo-be/utils/paginator"
	utilRes "web-qudo-be/utils/response"
	utilVal "web-qudo-be/utils/validator"
)

type MediaLibraryController struct {
	svc service.MediaLibraryService
}

func NewMediaLibraryController(svc service.MediaLibraryService) *MediaLibraryController {
	return &MediaLibraryController{svc: svc}
}

func (_i *MediaLibraryController) All(c *fiber.Ctx) error {
	clientID := middleware.GetClientID(c)
	user := middleware.GetUser(c)
	uid := 0
	if user != nil {
		uid = int(user.ID)
	}
	_ = uid

	paginate, err := paginator.Paginate(c)
	if err != nil {
		return err
	}
	q := strings.TrimSpace(c.Query("q"))
	var st *string
	if v := strings.TrimSpace(c.Query("source_type")); v != "" {
		st = &v
	}
	data, paging, err := _i.svc.All(clientID, q, st, paginate)
	if err != nil {
		return err
	}
	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Media library list"},
		Data:     data,
		Meta:     paging,
	})
}

func (_i *MediaLibraryController) Register(c *fiber.Ctx) error {
	clientID := middleware.GetClientID(c)
	user := middleware.GetUser(c)
	uid := 0
	if user != nil {
		uid = int(user.ID)
	}
	req := new(request.MediaLibraryRegisterRequest)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}
	if err := _i.svc.RegisterFromRequest(clientID, uid, req); err != nil {
		return err
	}
	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Registered to media library"},
	})
}

func (_i *MediaLibraryController) Upload(c *fiber.Ctx) error {
	clientID := middleware.GetClientID(c)
	user := middleware.GetUser(c)
	uid := 0
	if user != nil {
		uid = int(user.ID)
	}
	if err := _i.svc.Upload(clientID, uid, c); err != nil {
		return err
	}
	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"File uploaded and added to media library"},
	})
}

func (_i *MediaLibraryController) Delete(c *fiber.Ctx) error {
	clientID := middleware.GetClientID(c)
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil {
		return err
	}
	if err := _i.svc.Delete(clientID, uint(id)); err != nil {
		return err
	}
	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Media library entry removed"},
	})
}
