package services import ( "context" "errors" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "pkg.local/root/rpaas-core-service/internal/models" "pkg.local/root/rpaas-core-service/pkg/logging" "time" ) type CompanyService interface { RegisterCompany(body *models.CompanyRegisterBody) (*models.CompanyInfo, error) GetCompanyInfoByID(id string) (*models.CompanyInfo, error) GetAllCompanies() ([]*models.CompanyInfo, error) } type CompanyServiceImpl struct { companycollection *mongo.Collection ctx context.Context } func NewCompanyService(companycollection *mongo.Collection, ctx context.Context) CompanyService { return &CompanyServiceImpl{ companycollection: companycollection, ctx: ctx, } } func (c *CompanyServiceImpl) GetAllCompanies() ([]*models.CompanyInfo, error) { var result []*models.CompanyInfo cursor, err := c.companycollection.Find(c.ctx, bson.M{}) if err != nil { return nil, err } if err = cursor.All(c.ctx, &result); err != nil { for cursor.Next(c.ctx) { var company models.CompanyInfo err = cursor.Decode(&company) if err != nil { return nil, err } result = append(result, &company) } } if err = cursor.Err(); err != nil { return nil, err } cursor.Close(c.ctx) if len(result) == 0 { return nil, errors.New("no companies found") } return result, nil } func (c *CompanyServiceImpl) GetCompanyInfoByID(id string) (*models.CompanyInfo, error) { var existingCompanyInfo models.CompanyInfo err := c.companycollection.FindOne(c.ctx, bson.M{"company_id": id}).Decode(&existingCompanyInfo) if err != nil { if errors.Is(err, mongo.ErrNoDocuments) { return nil, err } } return &existingCompanyInfo, nil } func (c *CompanyServiceImpl) RegisterCompany(company *models.CompanyRegisterBody) (*models.CompanyInfo, error) { var existingCompany *models.CompanyInfo err := c.companycollection.FindOne(c.ctx, bson.M{"$or": []bson.M{{"username": company.Username}, {"email": bson.M{"$in": []string{company.Email}}}}}).Decode(&existingCompany) if err == nil { logging.Logger().Warn("Username or email already exists", err) return nil, errors.New("username or email already exists") } else if !errors.Is(err, mongo.ErrNoDocuments) { logging.Logger().Error(err) return nil, errors.New("InternalServerError") } companyInfo := &models.CompanyInfo{ CompanyID: primitive.NewObjectID().Hex(), CompanyName: company.CompanyName, CreateAt: time.Now().UTC().Round(time.Second), UpdateAt: time.Now().UTC().Round(time.Second), Country: company.Country, Username: company.Username, Owner: []string{company.Username}, Email: company.Email, FirstName: company.FirstName, LastName: company.LastName, Mobile: company.Mobile, } _, err = c.companycollection.InsertOne(c.ctx, companyInfo) return companyInfo, err }