package datasql

import (
	"context"
	"fmt"

	"gitlab.ost.ch/marketminds/marketminds/pkg/entity"
)

func (r *SqlRepository) GetAllNamedEntities() ([]*entity.NamedEntity, error) {
	rows, err := r.pool.Query(context.Background(), "SELECT name, type, createdat FROM marketminds.namedentity")
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var namedEntities []*entity.NamedEntity
	for rows.Next() {
		var namedEntity entity.NamedEntity
		err := rows.Scan(&namedEntity.Name, &namedEntity.EntityType, &namedEntity.CreatedAt)
		if err != nil {
			return nil, err
		}
		namedEntities = append(namedEntities, &namedEntity)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return namedEntities, nil
}

func (r *SqlRepository) GetNamedEntityByName(name string) (*entity.NamedEntity, error) {
	var entity entity.NamedEntity
	err := r.pool.QueryRow(context.Background(), "SELECT name, type, createdat FROM marketminds.namedentity WHERE name = $1 ORDER BY type, name ASC", name).Scan(&entity.Name, &entity.EntityType, &entity.CreatedAt)
	if err != nil {
		return nil, err
	}
	return &entity, nil
}

func (r *SqlRepository) GetOrCreateNamedEntity(newNamedEntity *entity.NamedEntity) (string, error) {
	nEntity, err := r.GetNamedEntityByName(newNamedEntity.Name)
	if err != nil {
		if err.Error() == "no rows in result set" {
			nEntityName, err := r.CreateNamedEntity(newNamedEntity)
			if err != nil {
				fmt.Println("Error creating named entity:", err)
				return "", err
			}
			return nEntityName, nil
		} else {
			fmt.Println("Error getting named entity:", err)
			return "", err
		}
	}
	return nEntity.Name, nil
}

func (r *SqlRepository) CreateNamedEntity(entity *entity.NamedEntity) (string, error) {
	query := `INSERT INTO marketminds.namedentity (name, type, createdat) VALUES ($1, $2, $3) RETURNING name`

	var name string
	err := r.pool.QueryRow(context.Background(), query, entity.Name, entity.EntityType, entity.CreatedAt).Scan(&name)
	if err != nil {
		return "", err
	}
	return name, nil
}

func (r *SqlRepository) UpdateNamedEntity(entity *entity.NamedEntity) error {
	_, err := r.pool.Exec(context.Background(), "UPDATE marketminds.namedentity SET type = $2, createdat = $3 WHERE name = $1", entity.Name, entity.EntityType, entity.CreatedAt)
	return err
}

func (r *SqlRepository) DeleteNamedEntity(name string) error {
	_, err := r.pool.Exec(context.Background(), "DELETE FROM marketminds.namedentity WHERE name = $1", name)
	return err
}
