package contact_field_template

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"wechat-api/ent/contactfieldtemplate"
	"wechat-api/ent/custom_types"
	"wechat-api/internal/utils/dberrorhandler"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *CreateContactFieldTemplateLogic) CreateContactFieldTemplate(req *types.ContactFieldTemplateInfo) (resp *types.BaseMsgResp, err error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	data, _ := l.svcCtx.DB.ContactFieldTemplate.Query().Where(contactfieldtemplate.OrganizationID(organizationId)).First(l.ctx)
	template := ConvertContactFieldTemplates(req.Template)
	if data != nil {
		err = l.svcCtx.DB.ContactFieldTemplate.
			Update().
			Where(contactfieldtemplate.OrganizationID(organizationId)).
			SetTemplate(template).
			Exec(l.ctx)
	} else {
		_, err = l.svcCtx.DB.ContactFieldTemplate.Create().
			SetOrganizationID(organizationId).
			SetTemplate(template).
			Save(l.ctx)
	}
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}
	return &types.BaseMsgResp{Msg: errormsg.CreateSuccess}, nil
}

func ConvertContactFieldTemplates(input []types.ContactFieldTemplate) []custom_types.ContactFieldTemplate {
	result := make([]custom_types.ContactFieldTemplate, len(input))
	for i, item := range input {
		options := make([]custom_types.ContactFieldTemplateOptions, len(item.Options))
		for j, opt := range item.Options {
			options[j] = custom_types.ContactFieldTemplateOptions{
				Label: opt.Label,
				Value: opt.Value,
			}
		}
		result[i] = custom_types.ContactFieldTemplate{
			Type:    item.Type,
			Id:      item.Id,
			Label:   item.Label,
			Options: options,
		}
	}
	return result
}
