package admin

import (
	"quyun/app/models"
	"quyun/app/requests"
	"quyun/providers/ali"

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

// @provider
type medias struct {
	oss *ali.OSSClient
}

// List medias
//
//	@Router	/admin/medias [get]
//	@Bind	pagination query
//	@Bind	query query
func (ctl *medias) List(ctx fiber.Ctx, pagination *requests.Pagination, query *ListQuery) (*requests.Pager, error) {
	cond := models.Medias.BuildConditionWithKey(query.Keyword)
	return models.Medias.List(ctx.Context(), pagination, cond)
}

// Show media
//
//	@Router	/admin/medias/:id [get]
//	@Bind	id path
func (ctl *medias) Show(ctx fiber.Ctx, id int64) error {
	media, err := models.Medias.GetByID(ctx.Context(), id)
	if err != nil {
		return ctx.SendString("Media not found")
	}

	url, err := ctl.oss.GetSignedUrl(ctx.Context(), media.Path)
	if err != nil {
		return err
	}

	return ctx.Redirect().To(url)
}

// Delete
//
//	@Router	/admin/medias/:id [delete]
//	@Bind	id path
func (ctl *medias) Delete(ctx fiber.Ctx, id int64) error {
	media, err := models.Medias.GetByID(ctx.Context(), id)
	if err != nil {
		return ctx.SendString("Media not found")
	}

	if err := ctl.oss.Delete(ctx.Context(), media.Path); err != nil {
		return err
	}

	if err := models.Medias.Delete(ctx.Context(), id); err != nil {
		return err
	}
	return ctx.SendStatus(fiber.StatusNoContent)
}
