package stats

import (
	"database/sql"

	"code.justin.tv/d8a/pg-healthcheck/common"
)

func NewRoleContainer(role string) RoleContainer {
	return &roleContainer{
		role: role,
	}
}

type RoleContainer interface {
	Role() string
	Refresh(db *sql.DB) error
}

type roleContainer struct {
	role string
}

func (rc *roleContainer) Role() string {
	return rc.role
}

func (rc *roleContainer) Refresh(db *sql.DB) error {
	rows, err := db.Query("select pg_is_in_recovery()")
	if err != nil {
		return err
	}
	defer common.CloseResource(rows)

	for rows.Next() {
		isReplica := false
		err := rows.Scan(&isReplica)
		if err != nil {
			return err
		}

		if isReplica {
			rc.role = "replica"
			return nil
		}
	}

	rc.role = "master"
	return nil
}
