package store

import "fmt"

// SetWorkloadGitOps toggles GitOps and sets the config path for a workload.
// Targeted column update (not UpdateWorkload) so it never clobbers the
// source_config / faces / webhook fields — and conversely, the edit-form save
// (UpdateWorkload) never touches these columns.
func (s *Store) SetWorkloadGitOps(id string, enabled bool, path string) error {
	if path == "" {
		path = ".tinyforge.yml"
	}
	result, err := s.db.Exec(
		`UPDATE workloads SET gitops_enabled=?, gitops_path=?, updated_at=? WHERE id=?`,
		BoolToInt(enabled), path, Now(), id,
	)
	if err != nil {
		return fmt.Errorf("set workload gitops: %w", err)
	}
	n, err := result.RowsAffected()
	if err != nil {
		return fmt.Errorf("rows affected: %w", err)
	}
	if n == 0 {
		return fmt.Errorf("workload %s: %w", id, ErrNotFound)
	}
	return nil
}

// RecordGitOpsSync stamps the commit SHA + timestamp of the last successful
// sync, so the UI can show "last synced <when> at <sha>".
func (s *Store) RecordGitOpsSync(id, commitSHA, syncedAt string) error {
	result, err := s.db.Exec(
		`UPDATE workloads SET gitops_last_sync_at=?, gitops_commit_sha=?, updated_at=? WHERE id=?`,
		syncedAt, commitSHA, Now(), id,
	)
	if err != nil {
		return fmt.Errorf("record gitops sync: %w", err)
	}
	n, err := result.RowsAffected()
	if err != nil {
		return fmt.Errorf("rows affected: %w", err)
	}
	if n == 0 {
		return fmt.Errorf("workload %s: %w", id, ErrNotFound)
	}
	return nil
}
