package queries

import (
	"backend/typesdefs"
	"fmt"
	"log"

	"github.com/georgysavva/scany/v2/pgxscan"
	"github.com/jackc/pgx/v5"
)

func SetVideosToDB(pool *[]typesdefs.UploadedMedia) error {
	if len(*pool) == 0 {
		log.Println("No new videos to save to DB.")
		return nil
	}
	batch := &pgx.Batch{}

	for _, data := range *pool {
		batch.Queue(`
			INSERT INTO public.videos_refs (codice, ordine, video, thumb, og_url)
			VALUES ($1, $2, $3, $4, $5)
			ON CONFLICT (codice, ordine) DO UPDATE SET video = $3, thumb = $4
		`, data.Codice, data.Order, data.MediaId, data.ThumbId, data.OGUrl)
	}

	if err := Db.Dbpool.SendBatch(Db.Ctx, batch).Close(); err != nil {
		return fmt.Errorf("failed to insert/update video batch: %w", err)
	}

	return nil
}

func GetVideosFromDB() ([]typesdefs.VideosRefs, error) {
	var videos []typesdefs.VideosRefs
	err := pgxscan.Select(Db.Ctx, Db.Dbpool, &videos, "SELECT * FROM public.videos_refs ORDER BY ordine ASC")
	if err != nil && err != pgx.ErrNoRows {
		return nil, fmt.Errorf("failed to get videos: %w", err)
	}
	return videos, nil
}

func GetCodiceVideosFromDB(codice string) ([]typesdefs.VideosRefs, error) {
	var videos []typesdefs.VideosRefs
	err := pgxscan.Select(Db.Ctx, Db.Dbpool, &videos, "SELECT * FROM public.videos_refs WHERE codice = $1 ORDER BY ordine ASC", codice)
	if err != nil && err != pgx.ErrNoRows {
		return nil, fmt.Errorf("failed to get videos: %w", err)
	}
	return videos, nil
}

func ClearVideosRefsByCodice(codice string) error {
	_, err := Db.Dbpool.Exec(Db.Ctx, "DELETE FROM public.videos_refs WHERE codice = $1", codice)
	if err != nil {
		return fmt.Errorf("failed to clear videos refs by codice: %w", err)
	}
	return nil
}
