package main

import (
	"context"
	"fmt"
	"os"

	"git.d-ma.be/mathias/tapir/internal/adapters/store"
)

// Env var names for the read-only CLI. DSN and user id are never hardcoded — the
// store holds confidential summaries, so the caller supplies both.
const (
	envDSN    = "TAPIR_DB_DSN"
	envUserID = "TAPIR_USER_ID"
)

// openStoreFromEnv reads TAPIR_DB_DSN and TAPIR_USER_ID and opens a store. The
// returned close func releases the pool; callers defer it. Both vars are
// required: an empty value is a usage error, not a silent default.
func openStoreFromEnv(ctx context.Context) (s *store.Store, userID string, closeFn func(), err error) {
	dsn := os.Getenv(envDSN)
	if dsn == "" {
		return nil, "", nil, fmt.Errorf("%s is required", envDSN)
	}
	userID = os.Getenv(envUserID)
	if userID == "" {
		return nil, "", nil, fmt.Errorf("%s is required", envUserID)
	}
	s, err = store.New(ctx, dsn)
	if err != nil {
		return nil, "", nil, err
	}
	return s, userID, s.Close, nil
}
