package postgres import ( "context" "errors" "fmt" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" "lincodex/backend/internal/adapter/secondary/postgres/sqlc" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) var _ outbound.NotificationInboxRepository = notificationInboxRepository{} // NewNotificationInboxRepository creates a direct store for inbox operations. // Transaction-bound callers can construct the same repository around the // queries of their current UnitOfWork. func NewNotificationInboxRepository(pool *pgxpool.Pool) outbound.NotificationInboxRepository { return notificationInboxRepository{queries: sqlc.New(pool)} } type notificationInboxRepository struct { queries *sqlc.Queries } func (repository notificationInboxRepository) Store( ctx context.Context, entry domain.NotificationInboxEntry, ) (bool, error) { const location = "notificationInboxRepository.Store" if err := validateInboxEntryForStore(entry); err != nil { return false, fmt.Errorf("%s - validate event: %w", location, err) } _, isRead := entry.ReadAt() if isRead { return false, fmt.Errorf("%s - a delivered event must be unread: %w", location, domain.ErrInvalidNotificationInboxEntry) } rows, err := repository.queries.InsertNotificationInboxEvent(ctx, sqlc.InsertNotificationInboxEventParams{ RecipientUserID: pgUUID(entry.RecipientUserID()), EventID: pgUUID(entry.EventID()), OrganizationID: pgUUID(entry.OrganizationID()), EventType: string(entry.EventType()), SchemaVersion: entry.SchemaVersion(), SourceType: string(entry.SourceType()), SourceID: pgUUID(entry.SourceID()), OccurredAt: pgTime(entry.OccurredAt()), }) if err != nil { return false, fmt.Errorf("%s - insert recipient event: %w", location, sanitizedDatabaseError(err)) } if rows == 1 { return true, nil } stored, err := repository.queries.GetNotificationInboxEvent(ctx, sqlc.GetNotificationInboxEventParams{ RecipientUserID: pgUUID(entry.RecipientUserID()), EventID: pgUUID(entry.EventID()), }) if errors.Is(err, pgx.ErrNoRows) { return false, fmt.Errorf("%s - duplicate event disappeared before comparison: %w", location, outbound.ErrNotificationInboxEntryNotFound) } if err != nil { return false, fmt.Errorf("%s - read duplicate event: %w", location, sanitizedDatabaseError(err)) } existing, err := notificationInboxEntryFromRow(stored) if err != nil { return false, fmt.Errorf("%s - restore duplicate event: %w", location, err) } if !sameNotificationInboxEvent(existing, entry) { return false, fmt.Errorf("%s - event ID has different immutable metadata: %w", location, outbound.ErrNotificationInboxEventConflict) } return false, nil } func (repository notificationInboxRepository) List( ctx context.Context, query outbound.NotificationInboxListQuery, ) (outbound.NotificationInboxPage, error) { const location = "notificationInboxRepository.List" if err := validateNotificationInboxListQuery(query); err != nil { return outbound.NotificationInboxPage{}, fmt.Errorf("%s - validate page: %w", location, err) } params := sqlc.ListNotificationInboxEventsParams{ RecipientUserID: pgUUID(query.RecipientUserID), OrganizationID: notificationInboxOptionalUUID(query.OrganizationID), AfterOccurredAt: pgOptionalTime(notificationInboxPositionTime(query.After)), AfterEventID: notificationInboxPositionID(query.After), PageLimit: query.Limit + 1, } rows, err := repository.queries.ListNotificationInboxEvents(ctx, params) if err != nil { return outbound.NotificationInboxPage{}, fmt.Errorf("%s - list recipient events: %w", location, sanitizedDatabaseError(err)) } page := outbound.NotificationInboxPage{HasMore: len(rows) > int(query.Limit)} if page.HasMore { rows = rows[:query.Limit] } page.Items = make([]domain.NotificationInboxEntry, 0, len(rows)) for _, row := range rows { entry, err := notificationInboxEntryFromRow(row) if err != nil { return outbound.NotificationInboxPage{}, fmt.Errorf("%s - restore event row: %w", location, err) } if entry.RecipientUserID() != query.RecipientUserID || (query.OrganizationID != nil && entry.OrganizationID() != *query.OrganizationID) { return outbound.NotificationInboxPage{}, fmt.Errorf("%s - database returned an event outside the recipient scope", location) } page.Items = append(page.Items, entry) } return page, nil } func (repository notificationInboxRepository) MarkRead( ctx context.Context, recipientUserID uuid.UUID, organizationID uuid.UUID, eventID uuid.UUID, at time.Time, ) (domain.NotificationInboxEntry, error) { const location = "notificationInboxRepository.MarkRead" if recipientUserID == uuid.Nil || organizationID == uuid.Nil || eventID == uuid.Nil || at.IsZero() { return domain.NotificationInboxEntry{}, fmt.Errorf("%s - recipient, organization, event, and read time are required: %w", location, domain.ErrInvalidNotificationInboxEntry) } row, err := repository.queries.MarkNotificationInboxEventRead(ctx, sqlc.MarkNotificationInboxEventReadParams{ RecipientUserID: pgUUID(recipientUserID), OrganizationID: pgUUID(organizationID), EventID: pgUUID(eventID), ReadAt: pgTime(at), }) if errors.Is(err, pgx.ErrNoRows) { return domain.NotificationInboxEntry{}, fmt.Errorf("%s - read event: %w", location, outbound.ErrNotificationInboxEntryNotFound) } if err != nil { return domain.NotificationInboxEntry{}, fmt.Errorf("%s - persist read time: %w", location, sanitizedDatabaseError(err)) } entry, err := notificationInboxEntryFromRow(row) if err != nil { return domain.NotificationInboxEntry{}, fmt.Errorf("%s - restore read event: %w", location, err) } return entry, nil } func validateInboxEntryForStore(entry domain.NotificationInboxEntry) error { _, err := domain.RestoreNotificationInboxEntry(domain.NotificationInboxEntryInput{ EventID: entry.EventID(), RecipientUserID: entry.RecipientUserID(), OrganizationID: entry.OrganizationID(), EventType: entry.EventType(), SchemaVersion: entry.SchemaVersion(), SourceType: entry.SourceType(), SourceID: entry.SourceID(), OccurredAt: entry.OccurredAt(), }) return err } func validateNotificationInboxListQuery(query outbound.NotificationInboxListQuery) error { if query.RecipientUserID == uuid.Nil || query.Limit < 1 || query.Limit > outbound.MaxNotificationInboxPageSize { return domain.ErrInvalidNotificationInboxEntry } if query.OrganizationID != nil && *query.OrganizationID == uuid.Nil { return domain.ErrInvalidNotificationInboxEntry } if query.After != nil && (query.After.EventID == uuid.Nil || query.After.OccurredAt.IsZero()) { return domain.ErrInvalidNotificationInboxEntry } return nil } func notificationInboxPositionTime(position *outbound.NotificationInboxPosition) *time.Time { if position == nil { return nil } return &position.OccurredAt } func notificationInboxPositionID(position *outbound.NotificationInboxPosition) pgtype.UUID { if position == nil { return pgtype.UUID{} } return pgUUID(position.EventID) } func notificationInboxOptionalUUID(value *uuid.UUID) pgtype.UUID { if value == nil { return pgtype.UUID{} } return pgUUID(*value) } func notificationInboxEntryFromRow(row sqlc.GetNotificationInboxEventRow) (domain.NotificationInboxEntry, error) { return restoreNotificationInboxEntryRow( row.RecipientUserID, row.EventID, row.OrganizationID, row.EventType, row.SchemaVersion, row.SourceType, row.SourceID, row.OccurredAt, row.ReadAt, ) } func notificationInboxEntryFromListRow(row sqlc.ListNotificationInboxEventsRow) (domain.NotificationInboxEntry, error) { return restoreNotificationInboxEntryRow( row.RecipientUserID, row.EventID, row.OrganizationID, row.EventType, row.SchemaVersion, row.SourceType, row.SourceID, row.OccurredAt, row.ReadAt, ) } func notificationInboxEntryFromReadRow(row sqlc.MarkNotificationInboxEventReadRow) (domain.NotificationInboxEntry, error) { return restoreNotificationInboxEntryRow( row.RecipientUserID, row.EventID, row.OrganizationID, row.EventType, row.SchemaVersion, row.SourceType, row.SourceID, row.OccurredAt, row.ReadAt, ) } func restoreNotificationInboxEntryRow( recipientUserID, eventID, organizationID pgtype.UUID, eventType string, schemaVersion int32, sourceType string, sourceID pgtype.UUID, occurredAt pgtype.Timestamptz, readAt pgtype.Timestamptz, ) (domain.NotificationInboxEntry, error) { if !recipientUserID.Valid || !eventID.Valid || !organizationID.Valid || !sourceID.Valid || !occurredAt.Valid || recipientUserID.Bytes == uuid.Nil || eventID.Bytes == uuid.Nil || organizationID.Bytes == uuid.Nil || sourceID.Bytes == uuid.Nil { return domain.NotificationInboxEntry{}, errors.New("postgres.restoreNotificationInboxEntryRow - stored identity or time is invalid") } var readAtValue *time.Time if readAt.Valid { value := readAt.Time readAtValue = &value } entry, err := domain.RestoreNotificationInboxEntry(domain.NotificationInboxEntryInput{ EventID: eventID.Bytes, RecipientUserID: recipientUserID.Bytes, OrganizationID: organizationID.Bytes, EventType: domain.NotificationInboxEventType(eventType), SchemaVersion: schemaVersion, SourceType: domain.NotificationInboxSourceType(sourceType), SourceID: sourceID.Bytes, OccurredAt: occurredAt.Time, ReadAt: readAtValue, }) if err != nil { return domain.NotificationInboxEntry{}, fmt.Errorf("postgres.restoreNotificationInboxEntryRow - restore metadata: %w", err) } return entry, nil } func sameNotificationInboxEvent(left, right domain.NotificationInboxEntry) bool { return left.EventID() == right.EventID() && left.RecipientUserID() == right.RecipientUserID() && left.OrganizationID() == right.OrganizationID() && left.EventType() == right.EventType() && left.SchemaVersion() == right.SchemaVersion() && left.SourceType() == right.SourceType() && left.SourceID() == right.SourceID() && left.OccurredAt().Equal(right.OccurredAt()) }