package queries

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

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

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

	for _, data := range *pool {
		batch.Queue(`
			INSERT INTO public.images_refs (codice, ordine, img, thumb, og_url)
			VALUES ($1, $2, $3, $4, $5)
			ON CONFLICT (codice, ordine) DO UPDATE SET img = $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 images batch: %w", err)
	}

	return nil
}

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

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

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