package mysql

import (
	"context"

	v1 "github.com/pingcap-inc/pinsights/model/v1"
	"gorm.io/gorm"
)

type groups struct {
	db *gorm.DB
}

func newGroups(ds *datastore) *groups {
	return &groups{db: ds.db}
}

func (u *groups) Create(ctx context.Context, group *v1.Group) error {
	return u.db.Create(&group).Error
}

func (u *groups) MCreate(ctx context.Context, groups *[]v1.Group) error {
	if len(*groups) == 0 {
		return nil
	}
	return u.db.Create(&groups).Error
}

func (u *groups) Update(ctx context.Context, group *v1.Group) error {
	return u.db.Save(&group).Error
}

func (u *groups) List() (*v1.GroupList, error) {
	res := &v1.GroupList{}
	d := u.db.
		Offset(0).
		Order("id desc").
		Find(&res.Items)
	return res, d.Error
}

func (u *groups) ListLarkDpts() (*v1.GroupList, error) {
	res := &v1.GroupList{}
	d := u.db.
		Where("type = ? AND sourceID <> ?", 1, "0").
		Offset(0).
		Order("id desc").
		Find(&res.Items)
	return res, d.Error
}

func (u *groups) DeleteByLarkDptID(ctx context.Context, larkdptid string) error {
	return u.db.Where("type = ? AND sourceID = ?", 1, larkdptid).Delete(&v1.Group{}).Error
}

func (u *groups) MDelete(ctx context.Context, ids []uint64) error {
	return u.db.Where("id IN (?)", ids).Delete(&v1.Group{}).Error
}

func (u *groups) Sync(ctx context.Context, news *[]v1.Group, updates []*v1.Group, delIds []uint64) error {
	tx := u.db.Begin()

	// new
	if len(*news) > 0 {
		err := tx.Create(news).Error
		if err != nil {
			tx.Rollback()
			return err
		}
	}

	// update
	for _, g := range updates {
		err := tx.Save(&g).Error
		if err != nil {
			tx.Rollback()
			return err
		}
	}

	// del
	err := tx.Where("id IN (?)", delIds).Delete(&v1.Group{}).Error
	if err != nil {
		tx.Rollback()
		return err
	}

	tx.Commit()

	return nil
}
