package admin_notification

import (
	"context"
	"database/sql"
	"time"

	"sim-server/app/main/api/internal/svc"
	"sim-server/app/main/api/internal/types"
	"sim-server/app/main/model"
	"sim-server/common/xerr"

	"github.com/google/uuid"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type AdminCreateNotificationLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAdminCreateNotificationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminCreateNotificationLogic {
	return &AdminCreateNotificationLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminCreateNotificationLogic) AdminCreateNotification(req *types.AdminCreateNotificationReq) (resp *types.AdminCreateNotificationResp, err error) {
	startDate, _ := time.Parse("2006-01-02", req.StartDate)
	endDate, _ := time.Parse("2006-01-02", req.EndDate)
	data := &model.GlobalNotifications{
		Id:               uuid.NewString(),
		Title:            req.Title,
		Content:          req.Content,
		NotificationPage: req.NotificationPage,
		StartDate:        sql.NullTime{Time: startDate, Valid: req.StartDate != ""},
		EndDate:          sql.NullTime{Time: endDate, Valid: req.EndDate != ""},
		StartTime:        req.StartTime,
		EndTime:          req.EndTime,
		Status:           req.Status,
	}
	result, err := l.svcCtx.GlobalNotificationsModel.Insert(l.ctx, nil, data)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建通知失败, err: %v, req: %+v", err, req)
	}
	_ = result
	return &types.AdminCreateNotificationResp{Id: data.Id}, nil
}
