package datasql

import (
	"context"

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

// GetAll returns all news channels
func (r *SqlRepository) GetAllNewsChannels() ([]*entity.NewsChannel, error) {
	rows, err := r.pool.Query(context.Background(), "SELECT * FROM marketminds.newschannel")
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var newsChannels []*entity.NewsChannel
	for rows.Next() {
		var channel *entity.NewsChannel = &entity.NewsChannel{}
		err := rows.Scan(&channel.Id, &channel.RssUrl,
			&channel.ImageUrl, &channel.Title, &channel.Link, &channel.Description,
			&channel.Language, &channel.Copyright,
			&channel.LastBuildDate, &channel.UpdatedAt, &channel.CreatedAt)
		if err != nil {
			return nil, err
		}
		newsChannels = append(newsChannels, channel)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return newsChannels, nil
}

func (r *SqlRepository) GetNewsChannelById(id string) (*entity.NewsChannel, error) {
	var newsChannel *entity.NewsChannel = &entity.NewsChannel{}
	query := "SELECT * FROM marketminds.newschannel WHERE id = $1"

	err := r.pool.QueryRow(context.Background(), query, id).Scan(
		&newsChannel.Id, &newsChannel.RssUrl, &newsChannel.ImageUrl,
		&newsChannel.Title, &newsChannel.Link, &newsChannel.Description,
		&newsChannel.Language, &newsChannel.Copyright,
		&newsChannel.LastBuildDate, &newsChannel.UpdatedAt, &newsChannel.CreatedAt,
	)

	if err != nil {
		return nil, err
	}

	return newsChannel, nil
}

func (r *SqlRepository) CreateNewsChannel(nc *entity.NewsChannel) error {
	query := `
		INSERT INTO marketminds.newschannel(
			rssurl, imageurl, title, link, description, language, copyright, lastbuilddate, updatedat, createdat)
			VALUES
	            ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) 
	        `
	_, err := r.pool.Exec(context.Background(), query,
		nc.RssUrl, nc.ImageUrl, nc.Title, nc.Link, nc.Description,
		nc.Language, nc.Copyright, nc.LastBuildDate,
		nc.UpdatedAt, nc.CreatedAt)

	if err != nil {
		return err
	}

	return nil
}
