// src/services/course-service.ts

// ...

	},

  findByName: async (name: string) => {
    const courses = await Course.findAll({
      attributes: ['id', 'name', 'synopsis', ['thumbnail_url', 'thumbnailUrl']],
      where: {
        name: {
          [Op.iLike]: `%${name}%`
        }
      }
    })

    return courses
  }
}

export { courseService }
// src/controllers/courses-controller.ts

	},

  // GET /courses/search?name=
  search: async (req: Request, res: Response) => {
    const { name } = req.query

    try {
			if (typeof name !== 'string') throw new Error('name param must be of type string');
      const courses = await courseService.findByName(name)
      return res.json(courses)
    } catch (err) {
      if (err instanceof Error) {
        return res.status(400).json({ message: err.message })
      }
    }
  }
}

export { coursesController }
// src/routes.ts

// ...

router.get('/courses/featured', coursesController.featured)
router.get('/courses/newest', coursesController.newest)
router.get('/courses/search', coursesController.search)
router.get('/courses/:id', coursesController.show)

export { router }
// src/controllers/courses-controller.ts

	},

  // GET /courses/search
  search: async (req: Request, res: Response) => {
    const { name } = req.query
    const [page, perPage] = getPaginationParams(req.query)

    try {
			if (typeof name !== 'string') throw new Error('name param must be of type string');
      const courses = await courseService.findByName(name, page, perPage)
      return res.json(courses)
    } catch (err) {
      if (err instanceof Error) {
        return res.status(400).json({ message: err.message })
      }
    }
  }
}

export { coursesController }
// src/services/course-service.ts

	},

  findByName: async (name: string, page: number, perPage: number) => {
    const offset = (page - 1) * perPage

    const { count, rows } = await Course.findAndCountAll({
      attributes: ['id', 'name', 'synopsis', ['thumbnail_url', 'thumbnailUrl']],
      where: {
        name: {
          [Op.iLike]: `%${name}%`
        }
      },
      limit: perPage,
      offset
    })

    return {
      courses: rows,
      page,
      perPage,
      total: count
    }
  }
}

export { courseService }