package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"

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

type ImageRefManager struct {
}

func NewImageRefManager() *ImageRefManager {
	return &ImageRefManager{}
}

func (i *ImageRefManager) GetImagesRef() ([]MiogestImagesRef_Table, error) {

	var images []MiogestImagesRef_Table

	err := pgxscan.Select(Db.Ctx, Db.Dbpool, &images, "SELECT * FROM public.miogest_images_ref")
	if err != nil {
		return nil, err
	}

	return images, nil
}

func (i *ImageRefManager) InsertImagesRef(annunci *AnnunciXML) error {

	batch := &pgx.Batch{}

	for _, annuncio := range annunci.Annuncio {
		batch.Queue(`
			INSERT INTO public.miogest_images_ref (codice, foto)
			VALUES ($1, $2)
			ON CONFLICT (codice) DO UPDATE SET foto = $2
		`, &annuncio.Codice, &annuncio.Foto)
	}

	if err := Db.Dbpool.SendBatch(Db.Ctx, batch).Close(); err != nil {
		return err
	}

	return nil
}

func (i *ImageRefManager) FindIsUpdate(annunci *AnnunciXML) ([]string, error) {
	r, err := i.GetImagesRef()
	if err != nil {
		return nil, err
	}
	refMap := make(map[string][]string) // Convert slice to map for faster lookup
	for _, ref := range r {
		if ref.Foto != nil {
			refMap[ref.Codice] = *ref.Foto
		}
	}

	var result []string
	for _, annuncio := range annunci.Annuncio {
		if annuncio.Codice != nil && annuncio.Foto != nil {
			refFoto, exists := refMap[*annuncio.Codice]
			if !exists {
				fmt.Println("new codice", *annuncio.Codice)
				result = append(result, *annuncio.Codice)
				continue
			}

			if len(*annuncio.Foto) != len(refFoto) {
				fmt.Println("Different length", *annuncio.Foto, refFoto)
				result = append(result, *annuncio.Codice)
				continue
			}

			for i, foto := range *annuncio.Foto {
				if foto != refFoto[i] {
					fmt.Println("Different content", *annuncio.Foto, refFoto)
					result = append(result, *annuncio.Codice)
					break
				}
			}
		}
	}
	return result, nil
}

func (i *ImageRefManager) ClearImages(to_clear []string) error {

	for _, codice := range to_clear {

		folder := filepath.Join(imgbasepath, codice)
		err := os.RemoveAll(folder)
		if err != nil {
			return err
		}

	}
	return nil
}

func (i *ImageRefManager) Reset() error {

	_, err := Db.Dbpool.Exec(Db.Ctx, "DELETE FROM public.miogest_images_ref")
	if err != nil {
		return err
	}

	_, err = Db.Dbpool.Exec(Db.Ctx, "UPDATE public.annunci SET url_immagini = NULL, url_video = NULL")
	if err != nil {
		return err
	}

	err = os.RemoveAll(imgbasepath)
	if err != nil {
		log.Fatal(err)
	}
	err = os.Mkdir(imgbasepath, 0755)
	if err != nil {
		log.Fatal(err)
	}

	return nil
}
