package store

import (
	"context"
	"strconv"

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

// Note is een reactie op een merge request.
// FilePath leeg is een algemene reactie. Suggestion is de vervangende tekst,
// BaseText de regels zoals ze bij het plaatsen in het bestand stonden.
type Note struct {
	ID         int64
	RepoID     int64
	MRID       int64
	AuthorID   int64
	Author     string
	Body       string
	FilePath   string
	LineStart  int
	LineEnd    int
	Suggestion string
	BaseText   string
	CreatedAt  time.Time
}

// AddNote bewaart een algemene reactie en telt hem als bijdrage.
func (s *Store) AddNote(ctx context.Context, repoID, mrID, authorID int64, body string) (Note, error) {
	return s.insertNote(ctx, repoID, mrID, authorID, body, "", 0, 0, "", "")
}

// AddLineNote bewaart een reactie op regels, optioneel met een suggestie.
func (s *Store) AddLineNote(ctx context.Context, repoID, mrID, authorID int64, body, path string, start, end int, suggestion, base string) (Note, error) {
	if path == "" || start < 1 || end < start {
		return Note{}, i18n.E("err.sugLines")
	}
	return s.insertNote(ctx, repoID, mrID, authorID, body, path, start, end, suggestion, base)
}

func (s *Store) insertNote(ctx context.Context, repoID, mrID, authorID int64, body, path string, start, end int, suggestion, base string) (Note, error) {
	body = strings.TrimSpace(body)
	if body == "" {
		return Note{}, i18n.E("err.noteEmpty")
	}
	limit := 4000
	if path != "" {
		limit = 20000
	}
	body = trim(body, limit)
	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, file_path, line_start, line_end, suggestion, base_text) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
		repoID, mrID, authorID, body, ts, path, start, end, suggestion, base)
	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,
		FilePath: path, LineStart: start, LineEnd: end, Suggestion: suggestion, BaseText: base,
		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, n.file_path, n.line_start, n.line_end, n.suggestion, n.base_text
		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, &n.FilePath, &n.LineStart, &n.LineEnd, &n.Suggestion, &n.BaseText); err != nil {
			return nil, err
		}
		n.CreatedAt = parseTime(created)
		out = append(out, n)
	}
	return out, rows.Err()
}
