package db

import (
	"fmt"
	"net/url"
	"path"
	"strings"
)

// RequirePostgresWorkpulse rejects DSNs that are not clearly scoped to database "workpulse".
func RequirePostgresWorkpulse(conn string) error {
	conn = strings.TrimSpace(conn)
	for _, tok := range strings.Fields(conn) {
		if tok == "dbname=workpulse" {
			return nil
		}
	}
	u, err := url.Parse(conn)
	if err == nil && (u.Scheme == "postgres" || u.Scheme == "postgresql") {
		if path.Base(strings.TrimSuffix(u.Path, "/")) == "workpulse" {
			return nil
		}
		if u.Query().Get("dbname") == "workpulse" {
			return nil
		}
	}
	return fmt.Errorf("refusing to connect: database name must be exactly %q (check dbname= or URL path)", "workpulse")
}
