package repository import ( "context" "errors" "fmt" dbgen "Yimaru-Backend/gen/db" "Yimaru-Backend/internal/domain" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" ) func examPrepPracticeParentFromDB(row dbgen.ExamPrepPracticeParent) domain.ExamPrepPracticeParent { return domain.ExamPrepPracticeParent{ Kind: domain.ExamPrepParentKind(row.ParentKind), ID: row.ParentID, } } func examPrepPracticeParentsFromDB(rows []dbgen.ExamPrepPracticeParent) []domain.ExamPrepPracticeParent { out := make([]domain.ExamPrepPracticeParent, 0, len(rows)) for _, row := range rows { out = append(out, examPrepPracticeParentFromDB(row)) } return out } func examPrepPracticeToDomain(p dbgen.ExamPrepLessonPractice, parents []domain.ExamPrepPracticeParent) domain.ExamPrepPractice { out := domain.ExamPrepPractice{ ID: p.ID, Parents: domain.ExamPrepPracticeParentsPtr(parents), Title: p.Title, QuestionSetID: p.QuestionSetID, PublishStatus: domain.PracticePublishStatusFromDB(p.PublishStatus), AuthoringProfile: domain.ParsePracticeAuthoringProfile(p.AuthoringProfile), } for _, parent := range parents { if parent.Kind == domain.ExamPrepParentKindLesson { id := parent.ID out.LessonID = &id break } } out.StoryDescription = fromPgText(p.StoryDescription) out.StoryImage = fromPgText(p.StoryImage) out.QuickTips = fromPgText(p.QuickTips) out.PersonaID = fromPgInt8ID(p.PersonaID) out.CreatedAt = p.CreatedAt.Time if p.UpdatedAt.Valid { t := p.UpdatedAt.Time out.UpdatedAt = &t } return out } func examPrepPracticeFromListRow(r dbgen.ExamPrepListPracticesByParentRow, parent domain.ExamPrepPracticeParent) domain.ExamPrepPractice { p := dbgen.ExamPrepLessonPractice{ ID: r.ID, Title: r.Title, StoryDescription: r.StoryDescription, StoryImage: r.StoryImage, PersonaID: r.PersonaID, QuestionSetID: r.QuestionSetID, QuickTips: r.QuickTips, PublishStatus: r.PublishStatus, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt, } return examPrepPracticeToDomain(p, []domain.ExamPrepPracticeParent{parent}) } func (s *Store) loadExamPrepPracticeParents(ctx context.Context, practiceID int64) ([]domain.ExamPrepPracticeParent, error) { rows, err := s.queries.ListExamPrepPracticeParentsByPracticeID(ctx, practiceID) if err != nil { return nil, err } return examPrepPracticeParentsFromDB(rows), nil } func (s *Store) insertExamPrepPracticeParent(ctx context.Context, q *dbgen.Queries, practiceID int64, parent domain.ExamPrepPracticeParent) error { _, err := q.InsertExamPrepPracticeParent(ctx, dbgen.InsertExamPrepPracticeParentParams{ PracticeID: practiceID, ParentKind: string(parent.Kind), ParentID: parent.ID, }) return err } func (s *Store) insertExamPrepPracticeParents(ctx context.Context, q *dbgen.Queries, practiceID int64, parents []domain.ExamPrepPracticeParent) error { for _, parent := range parents { if err := s.insertExamPrepPracticeParent(ctx, q, practiceID, parent); err != nil { return err } } return nil } func (s *Store) attachParentsToExamPrepPractices(ctx context.Context, practices []domain.ExamPrepPractice) ([]domain.ExamPrepPractice, error) { if len(practices) == 0 { return practices, nil } ids := make([]int64, len(practices)) for i, p := range practices { ids[i] = p.ID } rows, err := s.queries.ListExamPrepPracticeParentsByPracticeIDs(ctx, ids) if err != nil { return nil, err } accum := make(map[int64][]domain.ExamPrepPracticeParent, len(practices)) for _, row := range rows { accum[row.PracticeID] = append(accum[row.PracticeID], examPrepPracticeParentFromDB(row)) } for i, p := range practices { parents := accum[p.ID] practices[i].Parents = domain.ExamPrepPracticeParentsPtr(parents) for _, parent := range parents { if parent.Kind == domain.ExamPrepParentKindLesson { id := parent.ID practices[i].LessonID = &id break } } } return practices, nil } func examPrepPracticeFromListAllRow(r dbgen.ListAllExamPrepPracticesRow) domain.ExamPrepPractice { p := dbgen.ExamPrepLessonPractice{ ID: r.ID, Title: r.Title, StoryDescription: r.StoryDescription, StoryImage: r.StoryImage, PersonaID: r.PersonaID, QuestionSetID: r.QuestionSetID, QuickTips: r.QuickTips, PublishStatus: r.PublishStatus, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt, } return examPrepPracticeToDomain(p, nil) } func (s *Store) CreateExamPrepPractice(ctx context.Context, in domain.CreateExamPrepPracticeInput, parents []domain.ExamPrepPracticeParent) (domain.ExamPrepPractice, error) { ps := domain.ParsePracticePublishStatusInput(in.PublishStatus) q, tx, err := s.BeginTx(ctx) if err != nil { return domain.ExamPrepPractice{}, fmt.Errorf("begin tx: %w", err) } defer func() { _ = tx.Rollback(ctx) }() p, err := q.ExamPrepCreatePractice(ctx, dbgen.ExamPrepCreatePracticeParams{ Title: derefString(in.Title), StoryDescription: toPgText(in.StoryDescription), StoryImage: toPgText(in.StoryImage), PersonaID: int64PtrToPg8(in.PersonaID), QuestionSetID: in.QuestionSetID, QuickTips: toPgText(in.QuickTips), PublishStatus: string(ps), }) if err != nil { return domain.ExamPrepPractice{}, err } if err := s.insertExamPrepPracticeParents(ctx, q, p.ID, parents); err != nil { return domain.ExamPrepPractice{}, err } if err := tx.Commit(ctx); err != nil { return domain.ExamPrepPractice{}, fmt.Errorf("commit: %w", err) } return examPrepPracticeToDomain(p, parents), nil } func (s *Store) GetExamPrepLessonPracticeByID(ctx context.Context, id int64) (domain.ExamPrepPractice, error) { p, err := s.queries.ExamPrepGetLessonPracticeByID(ctx, id) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return domain.ExamPrepPractice{}, pgx.ErrNoRows } return domain.ExamPrepPractice{}, err } parents, err := s.loadExamPrepPracticeParents(ctx, id) if err != nil { return domain.ExamPrepPractice{}, err } return examPrepPracticeToDomain(p, parents), nil } func (s *Store) TryGetExamPrepLessonPracticeByQuestionSetID(ctx context.Context, questionSetID int64) (domain.ExamPrepPractice, bool, error) { p, err := s.queries.ExamPrepGetLessonPracticeByQuestionSetID(ctx, questionSetID) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return domain.ExamPrepPractice{}, false, nil } return domain.ExamPrepPractice{}, false, err } parents, err := s.loadExamPrepPracticeParents(ctx, p.ID) if err != nil { return domain.ExamPrepPractice{}, false, err } return examPrepPracticeToDomain(p, parents), true, nil } func (s *Store) ListExamPrepPracticesByParent(ctx context.Context, parent domain.ExamPrepPracticeParent, publishedOnly bool, limit, offset int32) ([]domain.ExamPrepPractice, int64, error) { rows, err := s.queries.ExamPrepListPracticesByParent(ctx, dbgen.ExamPrepListPracticesByParentParams{ Limit: optionalPositiveInt4(limit), Offset: optionalNonNegativeInt4(offset), ParentKind: string(parent.Kind), ParentID: parent.ID, PublishedOnly: publishedOnly, }) if err != nil { return nil, 0, err } if len(rows) == 0 { return []domain.ExamPrepPractice{}, 0, nil } var total int64 out := make([]domain.ExamPrepPractice, 0, len(rows)) for i, r := range rows { if i == 0 { total = r.TotalCount } out = append(out, examPrepPracticeFromListRow(r, parent)) } return out, total, nil } func (s *Store) ListAllExamPrepPractices(ctx context.Context, publishedOnly, unlinkedOnly bool, limit, offset int32) ([]domain.ExamPrepPractice, int64, error) { rows, err := s.queries.ListAllExamPrepPractices(ctx, dbgen.ListAllExamPrepPracticesParams{ PublishedOnly: publishedOnly, UnlinkedOnly: unlinkedOnly, Limit: optionalPositiveInt4(limit), Offset: optionalNonNegativeInt4(offset), }) if err != nil { return nil, 0, err } if len(rows) == 0 { return []domain.ExamPrepPractice{}, 0, nil } var total int64 out := make([]domain.ExamPrepPractice, 0, len(rows)) for i, r := range rows { if i == 0 { total = r.TotalCount } out = append(out, examPrepPracticeFromListAllRow(r)) } out, err = s.attachParentsToExamPrepPractices(ctx, out) if err != nil { return nil, 0, err } return out, total, nil } func (s *Store) ReplaceExamPrepPracticeParents(ctx context.Context, practiceID int64, parents []domain.ExamPrepPracticeParent) error { q, tx, err := s.BeginTx(ctx) if err != nil { return fmt.Errorf("begin tx: %w", err) } defer func() { _ = tx.Rollback(ctx) }() if err := q.DeleteExamPrepPracticeParentsByPracticeID(ctx, practiceID); err != nil { return err } if err := s.insertExamPrepPracticeParents(ctx, q, practiceID, parents); err != nil { return err } return tx.Commit(ctx) } func (s *Store) DeleteExamPrepPracticeParent(ctx context.Context, practiceID int64, parent domain.ExamPrepPracticeParent) (bool, error) { rows, err := s.queries.DeleteExamPrepPracticeParent(ctx, dbgen.DeleteExamPrepPracticeParentParams{ PracticeID: practiceID, ParentKind: string(parent.Kind), ParentID: parent.ID, }) if err != nil { return false, err } return rows > 0, nil } func (s *Store) CountExamPrepPracticesByParent(ctx context.Context, kind domain.ExamPrepParentKind, parentID int64) (int64, error) { return s.queries.CountExamPrepPracticesByParent(ctx, dbgen.CountExamPrepPracticesByParentParams{ ParentKind: string(kind), ParentID: parentID, }) } func (s *Store) CountExamPrepPracticesByParentExcludingPractice(ctx context.Context, kind domain.ExamPrepParentKind, parentID, excludePracticeID int64) (int64, error) { return s.queries.CountExamPrepPracticesByParentExcludingPractice(ctx, dbgen.CountExamPrepPracticesByParentExcludingPracticeParams{ ParentKind: string(kind), ParentID: parentID, PracticeID: excludePracticeID, }) } func (s *Store) UpdateExamPrepLessonPractice(ctx context.Context, id int64, input domain.UpdateExamPrepPracticeInput) (domain.ExamPrepPractice, error) { var titleText pgtype.Text if input.Title != nil { titleText = pgtype.Text{String: *input.Title, Valid: true} } qs := optionalInt8UpdateID(input.QuestionSetID) p, err := s.queries.ExamPrepUpdateLessonPractice(ctx, dbgen.ExamPrepUpdateLessonPracticeParams{ ID: id, Title: titleText, StoryDescription: optionalTextUpdate(input.StoryDescription), StoryImage: optionalTextUpdate(input.StoryImage), PersonaID: optionalInt8UpdateID(input.PersonaID), QuestionSetID: qs, QuickTips: optionalTextUpdate(input.QuickTips), PublishStatus: optionalPublishStatusUpdate(input.PublishStatus), AuthoringProfile: optionalAuthoringProfileUpdate(input.AuthoringProfile), }) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return domain.ExamPrepPractice{}, pgx.ErrNoRows } return domain.ExamPrepPractice{}, err } parents, err := s.loadExamPrepPracticeParents(ctx, id) if err != nil { return domain.ExamPrepPractice{}, err } return examPrepPracticeToDomain(p, parents), nil } func (s *Store) DeleteExamPrepLessonPractice(ctx context.Context, id int64) error { return s.queries.ExamPrepDeleteLessonPractice(ctx, id) } // optionalPositiveInt4 maps values <= 0 to SQL NULL (no LIMIT → return all rows). func optionalPositiveInt4(v int32) pgtype.Int4 { if v <= 0 { return pgtype.Int4{} } return pgtype.Int4{Int32: v, Valid: true} } // optionalNonNegativeInt4 maps values < 0 to SQL NULL; 0+ are sent as-is (NULL OFFSET ≡ 0). func optionalNonNegativeInt4(v int32) pgtype.Int4 { if v < 0 { return pgtype.Int4{} } return pgtype.Int4{Int32: v, Valid: true} }