package admin

import (
	"errors"
	"fmt"
	"path/filepath"

	"quyun/app/jobs"
	"quyun/app/models"
	"quyun/database/schemas/public/model"
	"quyun/providers/ali"
	"quyun/providers/app"
	"quyun/providers/job"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/go-jet/jet/v2/qrm"
	"github.com/gofiber/fiber/v3"
	log "github.com/sirupsen/logrus"
)

const UPLOAD_PATH = "quyun"

// @provider
type uploads struct {
	app *app.Config
	oss *ali.OSSClient
	job *job.Job
}

type PreCheckResp struct {
	Exists  bool               `json:"exists"`
	PreSign *oss.PresignResult `json:"pre_sign"`
}

// PreUploadCheck
//
//	@Router	/admin/uploads/pre-uploaded-check/:md5.:ext [get]
//	@Bind	md5 path
//	@Bind	ext path
//	@Bind	mime query
func (up *uploads) PreUploadCheck(ctx fiber.Ctx, md5, ext, mime string) (*PreCheckResp, error) {
	_, err := models.Medias.GetByHash(ctx.Context(), md5)
	if err != nil && errors.Is(err, qrm.ErrNoRows) {
		preSign, err := up.oss.PreSignUpload(ctx.Context(), fmt.Sprintf("%s.%s", md5, ext), mime)
		if err != nil {
			return nil, err
		}

		return &PreCheckResp{Exists: false, PreSign: preSign}, nil
	}

	return &PreCheckResp{Exists: true}, nil
}

type PostUploadedForm struct {
	OriginalName string `json:"originalName"`
	Md5          string `json:"md5"`
	MimeType     string `json:"mimeType"`
	Size         int64  `json:"size"`
}

// PostUploadedAction
//
//	@Router	/admin/uploads/post-uploaded-action [post]
//	@Bind	body body
func (up *uploads) PostUploadedAction(ctx fiber.Ctx, body *PostUploadedForm) error {
	m, err := models.Medias.GetByHash(ctx.Context(), body.Md5)
	if err != nil && !errors.Is(err, qrm.ErrNoRows) {
		return err
	}

	m = &model.Medias{
		Name:     body.OriginalName,
		MimeType: body.MimeType,
		Size:     body.Size,
		Hash:     body.Md5,
		Path:     filepath.Join(UPLOAD_PATH, body.Md5+filepath.Ext(body.OriginalName)),
	}
	if err := models.Medias.Create(ctx.Context(), m); err != nil {
		return err
	}

	if m.MimeType == "video/mp4" {
		if err := up.job.Add(&jobs.DownloadFromAliOSS{MediaHash: m.Hash}); err != nil {
			log.WithError(err).WithField("media", m).Errorf("add job failed")
		}
	}

	return nil
}
