package mysql

import (
	"context"

	"gorm.io/gorm"

	"data-platform/model"
)

type bqAccount struct {
	db *gorm.DB
}

func newBqAccount(ds *datastore) *bqAccount {
	return &bqAccount{db: ds.db}
}

func (a *bqAccount) List(_ context.Context) (records []model.BqAccount, err error) {
	err = a.db.Find(&records).Error
	return
}

// ListCurrentCRM resolves the current finance Account business number to the
// NexusCRM Account Id. The legacy bq_account table is sourced from the retired
// Salesforce snapshot and can omit newly-created NexusCRM Accounts.
func (a *bqAccount) ListCurrentCRM(ctx context.Context) (records []model.BqAccount, err error) {
	err = a.db.WithContext(ctx).
		Table("salesforce_account").
		Select("sf_id AS account_id, account_id AS account_name").
		Where("is_deleted = ?", false).
		Where("TRIM(COALESCE(sf_id, '')) <> ''").
		Where("TRIM(COALESCE(account_id, '')) <> ''").
		Scan(&records).Error
	return
}

func (a *bqAccount) Save(addRecords []model.BqAccount, upRecords []model.BqAccount, delRecords []model.BqAccount) error {

	if len(addRecords) > 0 {
		err := a.db.Create(&addRecords).Error
		if err != nil {
			return err
		}
	}
	if len(upRecords) > 0 {
		for _, record := range upRecords {
			err := a.db.Model(&record).Where("id = ?", record.ID).Updates(&record).Error
			if err != nil {
				return err
			}
		}
	}
	if len(delRecords) > 0 {
		for _, record := range delRecords {
			err := a.db.Delete(&record).Error
			if err != nil {
				return err
			}
		}
	}
	return nil
}
