package store

import (
	"context"
	"strconv"

	"gitlab.com/Timfa/bluegit/internal/i18n"
	"strings"
	"time"
)

// Note is een reactie op een merge request.
type Note struct {
	ID        int64
	RepoID    int64
	MRID      int64
	AuthorID  int64
	Author    string
	Body      string
	CreatedAt time.Time
}

// AddNote bewaart een reactie en telt hem als bijdrage.
func (s *Store) AddNote(ctx context.Context, repoID, mrID, authorID int64, body string) (Note, error) {
	body = strings.TrimSpace(body)
	if body == "" {
		return Note{}, i18n.E("err.noteEmpty")
	}
	body = trim(body, 4000)
	tx, err := s.db.BeginTx(ctx, nil)
	if err != nil {
		return Note{}, err
	}
	defer func() { _ = tx.Rollback() }()
	ts := now()
	res, err := tx.ExecContext(ctx, `INSERT INTO notes (repo_id, mr_id, author_id, body, created_at) VALUES (?, ?, ?, ?, ?)`,
		repoID, mrID, authorID, body, ts)
	if err != nil {
		return Note{}, err
	}
	id, _ := res.LastInsertId()
	if _, err := tx.ExecContext(ctx, `INSERT OR IGNORE INTO contributions (user_id, repo_id, kind, ref, occurred_at) VALUES (?, ?, 'comment', ?, ?)`,
		authorID, repoID, "note:"+strconv.FormatInt(id, 10), ts); err != nil {
		return Note{}, err
	}
	if err := tx.Commit(); err != nil {
		return Note{}, err
	}
	return Note{ID: id, RepoID: repoID, MRID: mrID, AuthorID: authorID, Body: body, CreatedAt: parseTime(ts)}, nil
}

// ListNotes geeft de reacties van één merge request, oudste eerst.
func (s *Store) ListNotes(ctx context.Context, mrID int64) ([]Note, error) {
	rows, err := s.db.QueryContext(ctx, `SELECT n.id, n.repo_id, n.mr_id, n.author_id, u.username, n.body, n.created_at
		FROM notes n JOIN users u ON u.id = n.author_id WHERE n.mr_id = ? ORDER BY n.id`, mrID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []Note
	for rows.Next() {
		var n Note
		var created string
		if err := rows.Scan(&n.ID, &n.RepoID, &n.MRID, &n.AuthorID, &n.Author, &n.Body, &created); err != nil {
			return nil, err
		}
		n.CreatedAt = parseTime(created)
		out = append(out, n)
	}
	return out, rows.Err()
}
