package repository

import (
	"context"

	sq "github.com/Masterminds/squirrel"

	"git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/helper/errors"
)

const articleTagTableName = "article_tag"

type ArticleTagRepository struct {
	db DB
}

func InitArticleTagRepository(db DB) *ArticleTagRepository {
	return &ArticleTagRepository{db: db}
}

func (a ArticleTagRepository) Add(
	ctx context.Context,
	articleID uint64,
	tagIDs []uint64,
) error {
	if len(tagIDs) == 0 {
		return nil
	}

	qb := sq.Insert(articleTagTableName).
		PlaceholderFormat(placeholder).
		Columns("article_id", "tag_id")

	for _, tagID := range tagIDs {
		qb = qb.Values(articleID, tagID)
	}

	q, v, err := qb.ToSql()
	if err != nil {
		return errors.Wrap(err, "build query")
	}

	_, err = a.db.ExecContext(ctx, q, v...)
	if err != nil {
		return errors.Wrap(err, "exec")
	}

	return nil
}

func (a ArticleTagRepository) Delete(
	ctx context.Context,
	articleID uint64,
	tagIDs []uint64,
) error {
	if len(tagIDs) == 0 {
		return nil
	}

	q, v, err := sq.Delete(articleTagTableName).
		PlaceholderFormat(placeholder).
		Where(sq.Eq{"article_id": articleID}).
		Where(sq.Eq{"tag_id": tagIDs}).
		ToSql()

	if err != nil {
		return errors.Wrap(err, "build query")
	}

	_, err = a.db.ExecContext(ctx, q, v...)
	if err != nil {
		return errors.Wrap(err, "exec")
	}

	return nil
}

func (a ArticleTagRepository) DeleteByArticleID(
	ctx context.Context,
	id uint64,
) error {
	q, v, err := sq.Delete(articleTagTableName).
		PlaceholderFormat(placeholder).
		Where(sq.Eq{"article_id": id}).
		ToSql()

	if err != nil {
		return errors.Wrap(err, "build query")
	}

	_, err = a.db.ExecContext(ctx, q, v...)
	if err != nil {
		return errors.Wrap(err, "exec")
	}

	return nil
}
