package common

import (
	"context"

	"github.guxuan/haibei/internal/config"

	"github.com/gin-gonic/gin"
	"github.guxuan/haibei/internal/mods/common/api"
	"github.guxuan/haibei/internal/mods/common/schema"
	"gorm.io/gorm"
)

type Common struct {
	DB                 *gorm.DB
	CommonAPI          *api.Common
	BannerAPI          *api.Banner
	NoticeAPI          *api.Notice
	CompanyAPI         *api.Company
	AreaAPI            *api.Area
	UploadAPI          *api.Upload
	ReceptionCenterAPI *api.ReceptionCenter
	SMSLogAPI          *api.SMSLog
}

func (a *Common) AutoMigrate(ctx context.Context) error {
	return a.DB.AutoMigrate(new(schema.Common), new(schema.Banner), new(schema.Notice), new(schema.Company), new(schema.Area), new(schema.ReceptionCenter), new(schema.SignIn), new(schema.SMSLog))
}

func (a *Common) Init(ctx context.Context) error {
	if config.C.Storage.DB.AutoMigrate {
		if err := a.AutoMigrate(ctx); err != nil {
			return err
		}
	}
	return nil
}

func (a *Common) RegisterV1Routers(ctx context.Context, v1 *gin.RouterGroup) error {
	common := v1.Group("commons")
	{
		common.GET("", a.CommonAPI.Query)
		common.GET(":id", a.CommonAPI.Get)
		common.POST("", a.CommonAPI.Create)
		common.PUT(":id", a.CommonAPI.Update)
		common.DELETE(":id", a.CommonAPI.Delete)
	}
	upload := v1.Group("upload")
	{
		upload.POST("", a.UploadAPI.SaveFile)

	}
	banner := v1.Group("banners")
	{
		banner.GET("", a.BannerAPI.Query)
		banner.GET(":id", a.BannerAPI.Get)
		banner.POST("", a.BannerAPI.Create)
		banner.PUT(":id", a.BannerAPI.Update)
		banner.DELETE(":id", a.BannerAPI.Delete)
	}
	notice := v1.Group("notices")
	{
		notice.GET("", a.NoticeAPI.Query)
		notice.GET(":id", a.NoticeAPI.Get)
		notice.POST("", a.NoticeAPI.Create)
		notice.PUT(":id", a.NoticeAPI.Update)
		notice.DELETE(":id", a.NoticeAPI.Delete)
	}
	company := v1.Group("companies")
	{
		company.GET("", a.CompanyAPI.Query)
		company.GET(":id", a.CompanyAPI.Get)
		company.POST("", a.CompanyAPI.Create)
		company.PUT(":id", a.CompanyAPI.Update)
		company.DELETE(":id", a.CompanyAPI.Delete)
	}
	area := v1.Group("areas")
	{
		area.GET("", a.AreaAPI.Query)
		area.GET(":id", a.AreaAPI.Get)
		area.POST("", a.AreaAPI.Create)
		area.PUT(":id", a.AreaAPI.Update)
		area.DELETE(":id", a.AreaAPI.Delete)
	}
	reception := v1.Group("reception_center")
	{
		reception.GET("", a.ReceptionCenterAPI.Query)
		reception.GET(":id", a.ReceptionCenterAPI.Get)
		reception.POST("", a.ReceptionCenterAPI.Create)
		reception.GET("qr_code/:id", a.ReceptionCenterAPI.GetQrCode)
		reception.POST("qr_code", a.ReceptionCenterAPI.CheckQrCode)
		reception.PUT(":id", a.ReceptionCenterAPI.Update)
		reception.DELETE(":id", a.ReceptionCenterAPI.Delete)
	}
	smsLog := v1.Group("smsLogs")
	{
		smsLog.GET("", a.SMSLogAPI.Query)
		smsLog.GET(":id", a.SMSLogAPI.Get)
		smsLog.PUT(":id", a.SMSLogAPI.Update)
		smsLog.DELETE(":id", a.SMSLogAPI.Delete)
	}
	return nil
}

func (a *Common) Release(ctx context.Context) error {
	return nil
}
