package reports

// Outlet scoping for the cashflow export (migration 000104).
//
// This is a DELIBERATE DUPLICATE of finance.cashflowStoreScope, and it is
// duplicated rather than exported from finance for one reason: internal/reports
// does not import internal/finance today, and introducing that dependency to
// share eleven lines would couple two unrelated modules — reports reads many
// tables finance does not own, and a finance change would then be able to break
// the reports build.
//
// The duplication is safe because the two copies are pinned against each other
// by TestCashflowStoreScopeMatchesFinance, which asserts the same resolution
// table. A drift between them would break a report, and that test is the thing
// that would notice.
//
// The alternative — a shared helper in internal/auth, next to StoreScope — was
// rejected because the decision encoded here (absent scope is a REFUSAL, not
// platform-wide) is a policy of two specific surfaces, not a fact about auth.
// Putting it in auth would quietly change the meaning for every caller of
// StoreScopeFrom.

import (
	"context"
	"errors"

	"github.com/TaruLab/keluargamart-backend/internal/auth"
)

// ErrNoStoreScope mirrors finance.ErrNoStoreScope. Denied rather than defaulted
// to platform-wide: see cashflowStoreScope in the finance package for the full
// argument, which is the same one and is not restated here.
var ErrNoStoreScope = errors.New("reports: no store scope on context")

// cashflowStoreScope resolves the caller's outlet scope for the cashflow export.
//
//	scope attached + platform-wide -> nil ids -> SQL NULL -> every row,
//	                                  including company-level
//	scope attached + restricted    -> those stores; store_id IS NULL excluded
//	no scope attached at all       -> ErrNoStoreScope (fail closed)
func cashflowStoreScope(ctx context.Context) ([]int64, error) {
	if !auth.HasStoreScope(ctx) {
		return nil, ErrNoStoreScope
	}
	return auth.StoreScopeFrom(ctx).IDs(), nil
}
