package middleware

import (
	"cold-delivery/common/middleware/handler"
	"errors"
	"github.com/gin-gonic/gin"
	"gogs.baozhida.cn/zoie/OAuth-core/api"
	"gogs.baozhida.cn/zoie/OAuth-core/pkg"
	"gogs.baozhida.cn/zoie/OAuth-core/pkg/response"
	"gorm.io/gorm"
)

// AuthCheckService 服务检查中间件
func AuthCheckService() gin.HandlerFunc {
	return func(c *gin.Context) {
		serviceId := c.Request.Header.Get("serviceId")
		log := api.GetRequestLogger(c)
		ormDB, err := pkg.GetOrm(c)
		if err != nil {
			log.Errorf("get db error, %s", err.Error())
			response.Error(c, 500, err, "数据库连接获取失败")
			return
		}
		service := handler.SysService{}

		err = ormDB.Table("sys_service").Where("id = ? ", serviceId).First(&service).Error
		if err != nil {
			log.Errorf("get service error, %s", err.Error())
			if errors.Is(err, gorm.ErrRecordNotFound) {
				response.Error(c, 400, err, "未认证")
				return
			}
			response.Error(c, 500, err, "数据库连接获取失败")
			return
		}
		if service.Status == 1 {
			response.Error(c, 400, err, "服务已停用")
			return
		}
		c.Next()

	}
}
