package vercel

import (
	"context"
	"errors"
	"fmt"

	perrors "github.com/pingcap/errors"
	"github.com/tidbcloud/pkgv2/tracing"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"gorm.io/gorm"
)

type TiDBVercelAccountDAO interface {
	AddVercelAccount(ctx context.Context, account TiDBVercelAccount) error
	GetVercelAccount(ctx context.Context, clusterID uint64, vercelProjectID, username string) (*TiDBVercelAccount, error)
}

type tiDBVercelAccountDAOImpl struct {
	db *gorm.DB
}

func NewTiDBVercelAccountDAO(db *gorm.DB) TiDBVercelAccountDAO {
	return &tiDBVercelAccountDAOImpl{
		db: db,
	}
}

func (d *tiDBVercelAccountDAOImpl) AddVercelAccount(ctx context.Context, account TiDBVercelAccount) (err error) {
	ctx, span := Tracer.Start(ctx, "tiDBVercelAccountDAOImpl.AddVercelAccount")
	defer func() {
		tracing.EndSpan(span, err)
	}()

	err = d.db.Create(&account).Error
	if err != nil {
		return perrors.Trace(err)
	}

	tilog.Info(ctx, fmt.Sprintf("Succeed to create account TiDBVercelAccount: %#v", account))
	return nil
}

func (d *tiDBVercelAccountDAOImpl) GetVercelAccount(ctx context.Context, clusterID uint64, vercelProjectID, username string) (_ *TiDBVercelAccount, err error) {
	_, span := Tracer.Start(ctx, "tiDBVercelAccountDAOImpl.GetVercelAccount")
	defer func() {
		tracing.EndSpan(span, err)
	}()

	var account TiDBVercelAccount
	err = d.db.Where("tidb_cluster_id = ? AND vercel_project_id = ? AND tidb_cluster_username = ?", clusterID, vercelProjectID, username).First(&account).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		} else {
			return nil, perrors.Trace(err)
		}
	}

	return &account, nil
}
