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 int64PtrToPg8(p *int64) pgtype.Int8 { if p == nil { return pgtype.Int8{Valid: false} } return pgtype.Int8{Int64: *p, Valid: true} } func fromPgInt8ID(c pgtype.Int8) *int64 { if !c.Valid { return nil } v := c.Int64 return &v } func optionalInt8UpdateID(val *int64) pgtype.Int8 { if val == nil { return pgtype.Int8{Valid: false} } return pgtype.Int8{Int64: *val, Valid: true} } func derefString(p *string) string { if p == nil { return "" } return *p } func lmsPracticeParentFromDB(row dbgen.LmsPracticeParent) domain.PracticeParent { return domain.PracticeParent{ Kind: domain.ParentKind(row.ParentKind), ID: row.ParentID, } } func lmsPracticeParentsFromDB(rows []dbgen.LmsPracticeParent) []domain.PracticeParent { out := make([]domain.PracticeParent, 0, len(rows)) for _, row := range rows { out = append(out, lmsPracticeParentFromDB(row)) } return out } func lmsPracticeToDomain(p dbgen.LmsPractice, parents []domain.PracticeParent) domain.Practice { out := domain.Practice{ ID: p.ID, Parents: domain.PracticeParentsPtr(parents), Title: p.Title, QuestionSetID: p.QuestionSetID, PublishStatus: domain.PracticePublishStatusFromDB(p.PublishStatus), } 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 (s *Store) loadLmsPracticeParents(ctx context.Context, practiceID int64) ([]domain.PracticeParent, error) { rows, err := s.queries.ListLmsPracticeParentsByPracticeID(ctx, practiceID) if err != nil { return nil, err } return lmsPracticeParentsFromDB(rows), nil } func (s *Store) attachParentsToPractices(ctx context.Context, practices []domain.Practice) ([]domain.Practice, 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.ListLmsPracticeParentsByPracticeIDs(ctx, ids) if err != nil { return nil, err } accum := make(map[int64][]domain.PracticeParent, len(practices)) for _, row := range rows { accum[row.PracticeID] = append(accum[row.PracticeID], lmsPracticeParentFromDB(row)) } for i, p := range practices { practices[i].Parents = domain.PracticeParentsPtr(accum[p.ID]) } return practices, nil } func (s *Store) insertLmsPracticeParents(ctx context.Context, q *dbgen.Queries, practiceID int64, parents []domain.PracticeParent) error { for _, parent := range parents { if _, err := q.InsertLmsPracticeParent(ctx, dbgen.InsertLmsPracticeParentParams{ PracticeID: practiceID, ParentKind: string(parent.Kind), ParentID: parent.ID, }); err != nil { return err } } return nil } func (s *Store) CreateLmsPractice( ctx context.Context, in domain.CreatePracticeInput, parents []domain.PracticeParent, ) (domain.Practice, error) { ps := domain.ParsePracticePublishStatusInput(in.PublishStatus) q, tx, err := s.BeginTx(ctx) if err != nil { return domain.Practice{}, fmt.Errorf("begin tx: %w", err) } defer func() { _ = tx.Rollback(ctx) }() p, err := q.CreateLmsPractice(ctx, dbgen.CreateLmsPracticeParams{ 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.Practice{}, err } if err := s.insertLmsPracticeParents(ctx, q, p.ID, parents); err != nil { return domain.Practice{}, err } if err := tx.Commit(ctx); err != nil { return domain.Practice{}, fmt.Errorf("commit: %w", err) } return lmsPracticeToDomain(p, parents), nil } func (s *Store) GetLmsPracticeByID(ctx context.Context, id int64) (domain.Practice, error) { p, err := s.queries.GetLmsPracticeByID(ctx, id) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return domain.Practice{}, pgx.ErrNoRows } return domain.Practice{}, err } parents, err := s.loadLmsPracticeParents(ctx, id) if err != nil { return domain.Practice{}, err } return lmsPracticeToDomain(p, parents), nil } // TryGetLmsPracticeByQuestionSetID returns false when no row exists. func (s *Store) TryGetLmsPracticeByQuestionSetID(ctx context.Context, questionSetID int64) (domain.Practice, bool, error) { p, err := s.queries.GetLmsPracticeByQuestionSetID(ctx, questionSetID) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return domain.Practice{}, false, nil } return domain.Practice{}, false, err } parents, err := s.loadLmsPracticeParents(ctx, p.ID) if err != nil { return domain.Practice{}, false, err } return lmsPracticeToDomain(p, parents), true, nil } func lmsPracticeFromListRow( id, qid int64, publishStatus, title string, sd, si, qt pgtype.Text, pid pgtype.Int8, ca, ua pgtype.Timestamptz, ) domain.Practice { return lmsPracticeToDomain(dbgen.LmsPractice{ ID: id, Title: title, StoryDescription: sd, StoryImage: si, PersonaID: pid, QuestionSetID: qid, QuickTips: qt, PublishStatus: publishStatus, CreatedAt: ca, UpdatedAt: ua, }, nil) } func (s *Store) ListLmsPracticesByCourseID(ctx context.Context, courseID int64, publishedOnly bool, limit, offset int32) ([]domain.Practice, int64, error) { rows, err := s.queries.ListLmsPracticesByCourseID(ctx, dbgen.ListLmsPracticesByCourseIDParams{ ParentID: courseID, PublishedOnly: publishedOnly, Limit: limit, Offset: offset, }) if err != nil { return nil, 0, err } if len(rows) == 0 { return []domain.Practice{}, 0, nil } var total int64 out := make([]domain.Practice, 0, len(rows)) for i, r := range rows { if i == 0 { total = r.TotalCount } out = append(out, lmsPracticeFromListRow( r.ID, r.QuestionSetID, r.PublishStatus, r.Title, r.StoryDescription, r.StoryImage, r.QuickTips, r.PersonaID, r.CreatedAt, r.UpdatedAt, )) } out, err = s.attachParentsToPractices(ctx, out) if err != nil { return nil, 0, err } return out, total, nil } func (s *Store) ListLmsPracticesByModuleID(ctx context.Context, moduleID int64, publishedOnly bool, limit, offset int32) ([]domain.Practice, int64, error) { rows, err := s.queries.ListLmsPracticesByModuleID(ctx, dbgen.ListLmsPracticesByModuleIDParams{ ParentID: moduleID, PublishedOnly: publishedOnly, Limit: limit, Offset: offset, }) if err != nil { return nil, 0, err } if len(rows) == 0 { return []domain.Practice{}, 0, nil } var total int64 out := make([]domain.Practice, 0, len(rows)) for i, r := range rows { if i == 0 { total = r.TotalCount } out = append(out, lmsPracticeFromListRow( r.ID, r.QuestionSetID, r.PublishStatus, r.Title, r.StoryDescription, r.StoryImage, r.QuickTips, r.PersonaID, r.CreatedAt, r.UpdatedAt, )) } out, err = s.attachParentsToPractices(ctx, out) if err != nil { return nil, 0, err } return out, total, nil } func (s *Store) ListLmsPracticesByLessonID(ctx context.Context, lessonID int64, publishedOnly bool, limit, offset int32) ([]domain.Practice, int64, error) { rows, err := s.queries.ListLmsPracticesByLessonID(ctx, dbgen.ListLmsPracticesByLessonIDParams{ ParentID: lessonID, PublishedOnly: publishedOnly, Limit: limit, Offset: offset, }) if err != nil { return nil, 0, err } if len(rows) == 0 { return []domain.Practice{}, 0, nil } var total int64 out := make([]domain.Practice, 0, len(rows)) for i, r := range rows { if i == 0 { total = r.TotalCount } out = append(out, lmsPracticeFromListRow( r.ID, r.QuestionSetID, r.PublishStatus, r.Title, r.StoryDescription, r.StoryImage, r.QuickTips, r.PersonaID, r.CreatedAt, r.UpdatedAt, )) } out, err = s.attachParentsToPractices(ctx, out) if err != nil { return nil, 0, err } return out, total, nil } func (s *Store) ListAllLmsPractices(ctx context.Context, publishedOnly, unlinkedOnly bool, limit, offset int32) ([]domain.Practice, int64, error) { rows, err := s.queries.ListAllLmsPractices(ctx, dbgen.ListAllLmsPracticesParams{ PublishedOnly: publishedOnly, UnlinkedOnly: unlinkedOnly, Limit: limit, Offset: offset, }) if err != nil { return nil, 0, err } if len(rows) == 0 { return []domain.Practice{}, 0, nil } var total int64 out := make([]domain.Practice, 0, len(rows)) for i, r := range rows { if i == 0 { total = r.TotalCount } out = append(out, lmsPracticeFromListRow( r.ID, r.QuestionSetID, r.PublishStatus, r.Title, r.StoryDescription, r.StoryImage, r.QuickTips, r.PersonaID, r.CreatedAt, r.UpdatedAt, )) } out, err = s.attachParentsToPractices(ctx, out) if err != nil { return nil, 0, err } return out, total, nil } func (s *Store) UpdateLmsPractice(ctx context.Context, id int64, input domain.UpdatePracticeInput) (domain.Practice, error) { var titleText pgtype.Text if input.Title != nil { titleText = pgtype.Text{String: *input.Title, Valid: true} } else { titleText = pgtype.Text{Valid: false} } qs := optionalInt8UpdateID(input.QuestionSetID) p, err := s.queries.UpdateLmsPractice(ctx, dbgen.UpdateLmsPracticeParams{ 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), }) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return domain.Practice{}, pgx.ErrNoRows } return domain.Practice{}, err } parents, err := s.loadLmsPracticeParents(ctx, id) if err != nil { return domain.Practice{}, err } return lmsPracticeToDomain(p, parents), nil } func (s *Store) ReplaceLmsPracticeParents(ctx context.Context, practiceID int64, parents []domain.PracticeParent) 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.DeleteLmsPracticeParentsByPracticeID(ctx, practiceID); err != nil { return err } if err := s.insertLmsPracticeParents(ctx, q, practiceID, parents); err != nil { return err } return tx.Commit(ctx) } func (s *Store) DeleteLmsPractice(ctx context.Context, id int64) error { return s.queries.DeleteLmsPractice(ctx, id) } func (s *Store) CountLmsPracticesByParent(ctx context.Context, kind domain.ParentKind, parentID int64) (int64, error) { return s.queries.CountLmsPracticesByParent(ctx, dbgen.CountLmsPracticesByParentParams{ ParentKind: string(kind), ParentID: parentID, }) } func (s *Store) CountLmsPracticesByParentExcludingPractice(ctx context.Context, kind domain.ParentKind, parentID, practiceID int64) (int64, error) { return s.queries.CountLmsPracticesByParentExcludingPractice(ctx, dbgen.CountLmsPracticesByParentExcludingPracticeParams{ ParentKind: string(kind), ParentID: parentID, PracticeID: practiceID, }) }