package postgresql

import (
	"context"
	"fmt"
	"time"
)

const getLastAlertCheckQuery = `select last_alert_check from alerter_state`

// GetLastAlertCheck returns the persisted time of the last completed alert check.
// Returns zero time if no check has been recorded yet (null in DB).
func (p *Postgresql) GetLastAlertCheck(ctx context.Context) (time.Time, error) {
	var t *time.Time
	err := p.db.QueryRow(ctx, getLastAlertCheckQuery).Scan(&t)
	if err != nil {
		return time.Time{}, fmt.Errorf("failed to exec getLastAlertCheckQuery: %w", err)
	}
	if t == nil {
		return time.Time{}, nil
	}
	return *t, nil
}

const setLastAlertCheckQuery = `update alerter_state set last_alert_check = $1`

func (p *Postgresql) SetLastAlertCheck(ctx context.Context, t time.Time) error {
	_, err := p.db.Exec(ctx, setLastAlertCheckQuery, t)
	if err != nil {
		return fmt.Errorf("failed to exec setLastAlertCheckQuery: %w", err)
	}
	return nil
}
