package store

import (
	"context"
	"strings"
	"time"
)

// Contribution is één getelde bijdrage.
type Contribution struct {
	UserID int64
	RepoID int64
	Kind   string
	Ref    string
	At     time.Time
}

// AddContributions bewaart bijdragen. Een herhaling van dezelfde ref telt niet opnieuw.
func (s *Store) AddContributions(ctx context.Context, rows []Contribution) error {
	if len(rows) == 0 {
		return nil
	}
	tx, err := s.db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer func() { _ = tx.Rollback() }()
	for _, row := range rows {
		if row.UserID == 0 || row.RepoID == 0 || row.Kind == "" || row.Ref == "" {
			continue
		}
		at := row.At.UTC()
		if at.IsZero() {
			at = time.Now().UTC()
		}
		if _, err := tx.ExecContext(ctx, `INSERT OR IGNORE INTO contributions (user_id, repo_id, kind, ref, occurred_at) VALUES (?, ?, ?, ?, ?)`,
			row.UserID, row.RepoID, row.Kind, row.Ref, at.Format(time.RFC3339)); err != nil {
			return err
		}
	}
	return tx.Commit()
}

// ContributionTimes geeft tijdstippen binnen de filter.
// userID 0 is iedereen. Een lege repolijst geeft niets terug.
func (s *Store) ContributionTimes(ctx context.Context, userID int64, repoIDs []int64, since time.Time) ([]time.Time, error) {
	if len(repoIDs) == 0 {
		return nil, nil
	}
	holders := make([]string, len(repoIDs))
	args := make([]any, 0, len(repoIDs)+2)
	args = append(args, since.UTC().Format(time.RFC3339))
	for i, id := range repoIDs {
		holders[i] = "?"
		args = append(args, id)
	}
	q := `SELECT occurred_at FROM contributions WHERE occurred_at >= ? AND repo_id IN (` + strings.Join(holders, ",") + `)`
	if userID != 0 {
		q += ` AND user_id = ?`
		args = append(args, userID)
	}
	rows, err := s.db.QueryContext(ctx, q, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []time.Time
	for rows.Next() {
		var raw string
		if err := rows.Scan(&raw); err != nil {
			return nil, err
		}
		out = append(out, parseTime(raw))
	}
	return out, rows.Err()
}

// ContributionSynced meldt of de bestaande commits van een repository al zijn overgenomen.
func (s *Store) ContributionSynced(ctx context.Context, repoID int64) (bool, error) {
	var n int
	err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM contribution_sync WHERE repo_id = ?`, repoID).Scan(&n)
	return n > 0, err
}

// MarkContributionSynced onthoudt dat de bestaande commits zijn overgenomen.
func (s *Store) MarkContributionSynced(ctx context.Context, repoID int64) error {
	_, err := s.db.ExecContext(ctx, `INSERT OR REPLACE INTO contribution_sync (repo_id, synced_at) VALUES (?, ?)`, repoID, now())
	return err
}

// DropContributions wist de telling van één repository, zodat die opnieuw uit git komt.
func (s *Store) DropContributions(ctx context.Context, repoID int64) error {
	if _, err := s.db.ExecContext(ctx, `DELETE FROM contributions WHERE repo_id = ?`, repoID); err != nil {
		return err
	}
	_, err := s.db.ExecContext(ctx, `DELETE FROM contribution_sync WHERE repo_id = ?`, repoID)
	return err
}

// UserByGitEmail koppelt het lokale deel van een auteur-e-mail aan een gebruikersnaam.
// Er is geen e-mailkolom: ada@example.com hoort bij de gebruiker ada.
// Een waarde zonder @ telt niet, en de git-auteurnaam telt niet.
func (s *Store) UserByGitEmail(ctx context.Context, email string) (User, bool) {
	local, ok := emailLocal(email)
	if !ok {
		return User{}, false
	}
	u, err := s.UserByUsername(ctx, local)
	if err != nil {
		return User{}, false
	}
	return u, true
}

// UserIDByGitAuthor is UserByGitEmail als alleen het id nodig is.
func (s *Store) UserIDByGitAuthor(ctx context.Context, email string) (int64, bool) {
	u, ok := s.UserByGitEmail(ctx, email)
	if !ok {
		return 0, false
	}
	return u.ID, true
}

func emailLocal(email string) (string, bool) {
	email = strings.ToLower(strings.TrimSpace(email))
	i := strings.LastIndex(email, "@")
	if i <= 0 || i == len(email)-1 {
		return "", false
	}
	local := email[:i]
	if local == "" || strings.ContainsAny(local, " @") {
		return "", false
	}
	return local, true
}
