package datasql

import (
	"context"
	"fmt"

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

func (r *SqlRepository) GetAllNERResults() ([]entity.NERResult, error) {
	rows, err := r.pool.Query(context.Background(), "SELECT * FROM marketminds.nerresult")
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var newsChannels []entity.NERResult
	for rows.Next() {
		var nerResult entity.NERResult
		err := rows.Scan(
			&nerResult.Id,
			&nerResult.CreatedAt,
			&nerResult.NewsItemId,
			&nerResult.NamedEntityId,
		)
		if err != nil {
			return nil, err
		}
		newsChannels = append(newsChannels, nerResult)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return newsChannels, nil
}

func (r *SqlRepository) GetNERResultByNewsItemId(id int64) ([]*entity.NERResult, error) {
	query := `SELECT * FROM marketminds.nerresult WHERE "newsitemId" = $1`
	rows, err := r.pool.Query(context.Background(), query, id)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var nerResults []*entity.NERResult
	for rows.Next() {
		var nerResult entity.NERResult
		err := rows.Scan(
			&nerResult.Id,
			&nerResult.CreatedAt,
			&nerResult.NewsItemId,
			&nerResult.NamedEntityId,
		)
		if err != nil {
			return nil, err
		}
		nerResults = append(nerResults, &nerResult)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return nerResults, nil
}

func (r *SqlRepository) CreateNERResult(nerResult *entity.NERResult) error {
	query := `
	insert into marketminds.nerresult (
		createdat, 
		"newsitemId", 
		"namedentityName"
	)
	VALUES
	( 
	  $1, $2, $3
	)
`
	_, err := r.pool.Exec(context.Background(), query,
		nerResult.CreatedAt,
		nerResult.NewsItemId,
		nerResult.NamedEntityId,
	)

	if err != nil {
		return err
	}
	fmt.Println("News Item created")
	return nil
}

func (r *SqlRepository) UpdateNERREsult(nerResult *entity.NERResult) error {
	query := `
	UPDATE marketminds.nerresult
	SET 
	createdat=$1, 
	"newsitemId"=$2, 
	"namedentityName"=$3, 
	WHERE id=$14
	`
	_, err := r.pool.Exec(context.Background(), query,
		nerResult.CreatedAt,
		nerResult.NewsItemId,
		nerResult.NamedEntityId,
		nerResult.Id)

	if err != nil {
		return err
	}
	return nil
}

func (r *SqlRepository) DeleteNERResult(id int) error {
	_, err := r.pool.Exec(context.Background(), "DELETE FROM marketminds.nerresult WHERE id=$1", id)
	if err != nil {
		return err
	}
	return nil
}
