package handler

import (
	"context"
	"encoding/json"
	"fmt"
	"kontor-api-fiber/pkg/schema"
	"log"
	"time"

	"github.com/gofiber/fiber/v2"
	"github.com/google/uuid"
	"github.com/uptrace/bun"
)

func SetupMediaRoutes(api fiber.Router) {
	media := api.Group("/media")
	media.Get("/files", GetAllFiles)
	media.Post("/files", AddFile)
}

func GetAllFiles(c *fiber.Ctx) error {
	var files []schema.MediaFile
	var err error
	var db *bun.DB
	ctx := context.Background()

	db, err = schema.GetDatabase()
	if err != nil {
		log.Fatal(err)
	}
	err = db.NewSelect().Model(&files).Relation("MediaActorFiles").Scan(ctx)
	if err != nil {
		log.Fatal(err)
		return fiber.NewError(fiber.StatusInternalServerError)
	}

	return c.JSON(files)
}

func AddFile(c *fiber.Ctx) error {
	var err error
	var db *bun.DB
	ctx := context.Background()
	var payload map[string]interface{}
	if err = json.Unmarshal(c.Body(), &payload); err != nil {
		return err
	}
	link := payload["url"]
	log.Printf("URL %s has been sent", link)

	db, err = schema.GetDatabase()
	if err != nil {
		log.Fatal(err)
	}
	id := uuid.NewString()
	timestamp := time.Now()
	mediafile := &schema.MediaFile{ID: id, CreatedAt: timestamp, UpdatedAt: timestamp, WebLink: fmt.Sprintf("%s", link), Version: 1, ShouldDownload: true, Review: true}
	_, err = db.NewInsert().Model(mediafile).Exec(ctx)
	if err != nil {
		return err
	}
	return c.SendStatus(201)
}
