package geo

import (
	"context"
	"errors"
	"fmt"

	"galaxy/backend/internal/postgres/jet/backend/table"

	"github.com/go-jet/jet/v2/postgres"
	"github.com/google/uuid"
)

// OnUserDeleted removes every `backend.user_country_counters` row for
// userID. It is the geo-side leg of the soft-delete cascade documented
// in `backend/PLAN.md` §5.2 / §5.8 and is invoked from
// `backend/internal/user.Service.SoftDelete` after the
// `accounts.deleted_at` write commits.
//
// The DELETE is idempotent: re-running on a user with no counters is a
// successful no-op. Errors from the database are wrapped with the geo
// prefix so caller logs identify the source.
func (s *Service) OnUserDeleted(ctx context.Context, userID uuid.UUID) error {
	if s == nil {
		return errors.New("geo: nil service")
	}
	if userID == uuid.Nil {
		return errors.New("geo: nil user id")
	}
	stmt := table.UserCountryCounters.DELETE().
		WHERE(table.UserCountryCounters.UserID.EQ(postgres.UUID(userID)))
	if _, err := stmt.ExecContext(ctx, s.db); err != nil {
		return fmt.Errorf("geo: delete counters for %s: %w", userID, err)
	}
	return nil
}
