package identity

import (
	"context"

	platformid "aigateway.local/core/internal/platform/id"
)

// InsertOutboxEvent 发布一条 outbox 事件(供通知 worker 消费)。
func (r *Repository) InsertOutboxEvent(ctx context.Context, eventType, aggregateType, aggregateID string, payload []byte) error {
	if r.pool == nil {
		return ErrUnavailable
	}
	eventID, err := platformid.NewUUID()
	if err != nil {
		return err
	}
	_, err = r.pool.Exec(ctx, `INSERT INTO gateway.outbox_events(event_id,event_type,event_version,aggregate_type,aggregate_id,payload) VALUES($1,$2,1,$3,$4,$5)`, eventID, eventType, aggregateType, aggregateID, payload)
	return mapRepositoryError(err)
}

// SecurityPrefs 返回登录通知偏好;未配置时默认开启。
func (r *Repository) SecurityPrefs(ctx context.Context, portalUserID string) (bool, error) {
	var loginNotify bool
	err := r.pool.QueryRow(ctx, `SELECT COALESCE((SELECT login_notify FROM gateway.portal_security_prefs WHERE portal_user_id=$1),true)`, portalUserID).Scan(&loginNotify)
	return loginNotify, mapRepositoryError(err)
}

// SetSecurityPrefs 更新登录通知偏好。
func (r *Repository) SetSecurityPrefs(ctx context.Context, portalUserID string, loginNotify bool) error {
	_, err := r.pool.Exec(ctx, `INSERT INTO gateway.portal_security_prefs(portal_user_id,login_notify) VALUES($1,$2)
		ON CONFLICT(portal_user_id) DO UPDATE SET login_notify=$2,updated_at=clock_timestamp()`, portalUserID, loginNotify)
	return mapRepositoryError(err)
}
