package db

import (
	"time"

	"crypto-miner-server/internal/models"
)

// PurgeHashrateSamplesBefore deletes samples older than cutoff.
func (d *Database) PurgeHashrateSamplesBefore(cutoff time.Time) (int64, error) {
	res, err := d.Exec("DELETE FROM hashrate_samples WHERE timestamp < ?", cutoff)
	if err != nil {
		return 0, err
	}
	return res.RowsAffected()
}

// ListBuildsOlderThan returns build records created before cutoff.
func (d *Database) ListBuildsOlderThan(cutoff time.Time) ([]*models.BuildRecord, error) {
	rows, err := d.Query(`SELECT `+buildSelectCols+` FROM builds WHERE created_at < ?`, cutoff)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []*models.BuildRecord
	for rows.Next() {
		b, err := scanBuild(rows)
		if err != nil {
			return nil, err
		}
		out = append(out, b)
	}
	return out, nil
}

// DeleteBuild removes a build record by id.
func (d *Database) DeleteBuild(id string) error {
	_, err := d.Exec("DELETE FROM builds WHERE id = ?", id)
	return err
}
