package msp

import (
	"context"

	"github.com/tidbcloud/account/internel/dao/entity"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

type MspConfigFilter struct {
	IDs    []entity.ID
	OrgIDs []entity.ID
	Status []entity.EntityStatus
}

type Advertising struct {
	Index   uint8  `json:"index"`
	Heading string `json:"heading"`
	Body    string `json:"body"`
}

type MspConfigDto struct {
	entity.MspConfig
	Advertisings []Advertising
}

func (d *MspDao) GetMspConfigByOrgID(ctx context.Context, tx *gorm.DB, orgID entity.ID) (*entity.MspConfig, error) {
	var mspConfig entity.MspConfig
	err := entity.NewMspConfigQuerySet(tx).OrgIDEq(orgID).One(&mspConfig)

	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	if err == gorm.ErrRecordNotFound {

		return nil, nil
	}

	return &mspConfig, nil
}

func (d *MspDao) CreateMspConfig(ctx context.Context, tx *gorm.DB, mspOrgConfig *entity.MspConfig) error {
	err := tx.Create(mspOrgConfig).Error
	if err != nil {
		return err
	}
	tilog.Info(ctx, "MspConfigDao CreateMspConfig success: ", zap.Any("mspOrgConfig: ", mspOrgConfig))

	return nil
}

func (d *MspDao) UpdateMspConfig(ctx context.Context, tx *gorm.DB, c entity.MspConfig) error {
	updater := entity.NewMspConfigQuerySet(tx).OrgIDEq(c.OrgID).GetUpdater()
	if c.Website != "" {
		updater.SetWebsite(c.Website)
	}

	if c.LogoName != "" {
		updater.SetLogoName(c.LogoName)
	}
	if c.DarkLogoName != "" {
		updater.SetDarkLogoName(c.DarkLogoName)
	}
	if c.Advertising != "" {
		updater.SetAdvertising(c.Advertising)
	}
	if c.Status != "" {
		updater.SetStatus(c.Status)
	}

	err := updater.Update()

	if err != nil {
		return err
	}
	return nil
}

func (d *MspDao) ListMspConfigs(ctx context.Context, tx *gorm.DB, filter MspConfigFilter) ([]entity.MspConfig, error) {
	var objs []entity.MspConfig
	/*
		if len(filter.IDs) == 0 && len(filter.orgIDs) == 0 && len(filter.status) == 0 {
			tilog.Info(ctx, "ListMspConfigs is nil ", zap.Error(nil))
			return nil, errs.NewBadRequest("ListMspConfigs must not null", nil)
		}

	*/qs := entity.NewMspConfigQuerySet(tx)

	if len(filter.IDs) > 0 {
		qs = qs.IDIn(filter.IDs...)
	}
	if len(filter.OrgIDs) > 0 {
		qs = qs.OrgIDIn(filter.OrgIDs...)
	}
	if len(filter.Status) > 0 {
		qs = qs.StatusIn(filter.Status...)
	}

	qs = qs.OrderDescByCreatedAt()
	err := qs.All(&objs)
	if err != nil && err != gorm.ErrRecordNotFound {
		tilog.Error(ctx, "ListMspConfigs fail", zap.Error(err))
		return nil, err
	}
	tilog.Info(ctx, "ListMspConfigs ", zap.Any("result", objs), zap.Any("filter", filter))
	return objs, nil
}
