package registry import ( "context" "database/sql" "strings" "reanimator/internal/domain" "reanimator/internal/idgen" ) type LotRepository struct { db *sql.DB idgen *idgen.Generator } func NewLotRepository(db *sql.DB) *LotRepository { return &LotRepository{ db: db, idgen: idgen.NewGenerator(db), } } func (r *LotRepository) Create(ctx context.Context, code string, description *string) (domain.Lot, error) { // Generate string ID id, err := r.idgen.Generate(ctx, idgen.Lot) if err != nil { return domain.Lot{}, err } _, err = r.db.ExecContext(ctx, `INSERT INTO lots (id, code, description) VALUES (?, ?, ?)`, id, code, description, ) if err != nil { return domain.Lot{}, classifyError(err) } return r.Get(ctx, id) } func (r *LotRepository) Get(ctx context.Context, id string) (domain.Lot, error) { var lot domain.Lot var description sql.NullString row := r.db.QueryRowContext(ctx, `SELECT id, code, description, created_at, updated_at FROM lots WHERE id = ?`, id, ) if err := row.Scan(&lot.ID, &lot.Code, &description, &lot.CreatedAt, &lot.UpdatedAt); err != nil { if err == sql.ErrNoRows { return domain.Lot{}, ErrNotFound } return domain.Lot{}, err } lot.Description = nullStringToPtr(description) return lot, nil } func (r *LotRepository) List(ctx context.Context) ([]domain.Lot, error) { rows, err := r.db.QueryContext(ctx, `SELECT id, code, description, created_at, updated_at FROM lots ORDER BY created_at DESC`, ) if err != nil { return nil, err } defer rows.Close() lots := make([]domain.Lot, 0) for rows.Next() { var lot domain.Lot var description sql.NullString if err := rows.Scan(&lot.ID, &lot.Code, &description, &lot.CreatedAt, &lot.UpdatedAt); err != nil { return nil, err } lot.Description = nullStringToPtr(description) lots = append(lots, lot) } if err := rows.Err(); err != nil { return nil, err } return lots, nil } func (r *LotRepository) EnsureByCode(ctx context.Context, code string) (domain.Lot, error) { normalized := strings.TrimSpace(code) if normalized == "" { return domain.Lot{}, ErrNotFound } var id string err := r.db.QueryRowContext(ctx, `SELECT id FROM lots WHERE code = ? LIMIT 1`, normalized, ).Scan(&id) if err == nil { return r.Get(ctx, id) } if err != sql.ErrNoRows { return domain.Lot{}, err } return r.Create(ctx, normalized, nil) }