package db

import (
	"chainweaver.org.cn/chainweaver/did/did-mgr-common-service/internal/config"
	"context"
	"time"
)

func FindContactsInfo() (*ContactsInfo, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	contractsInfo := &ContactsInfo{}
	count := int64(0)

	tx := config.DB.WithContext(ctx)
	tx = tx.Order("created_at desc")
	err := tx.First(contractsInfo).Offset(-1).Limit(-1).Count(&count).Error
	if err != nil {
		return nil, err
	}

	return contractsInfo, nil
}

func FindContactsInfoByOrgId(orgId int64) (*ContactsInfo, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	contractsInfo := &ContactsInfo{}
	tx := config.DB.WithContext(ctx)
	if err := tx.Where("org_id = ?", orgId).First(contractsInfo).Error; err != nil {
		return nil, err
	}
	return contractsInfo, nil
}

func UpdateContactsInfo(info *ContactsInfo) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	return config.DB.WithContext(ctx).Model(info).Where("id = ?", info.Id).Updates(info).Error
}