package mysql

import (
	"context"

	"gorm.io/gorm"

	"github.com/pingcap-inc/data-ingestion-tools/model"
)

type createdCollection struct {
	db *gorm.DB
}

func newCreatedCollection(ds *datastore) *createdCollection {
	return &createdCollection{db: ds.db}
}

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

func (c *createdCollection) ListCurrentMonth(_ context.Context, billMonth string) (records []*model.CreatedCollection, err error) {
	err = c.db.Where("bill_month = ?", billMonth).Find(&records).Error
	return
}

func (c *createdCollection) Update(_ context.Context, record *model.CreatedCollection) error {
	return c.db.Save(record).Error
}

func (c *createdCollection) DeleteAndSave(_ context.Context, records []model.CreatedCollection) ([]model.CreatedCollection, error) {
	if len(records) == 0 {
		return nil, nil
	}
	// clear the records of the current month
	c.db.Where("bill_month = ? and sync = ?", records[0].BillMonth, 0).Unscoped().Delete(&model.CreatedCollection{})

	dRecords := make([]model.CreatedCollection, 0)
	for _, record := range records {
		var tmpCollection model.CreatedCollection
		err := c.db.Where("bill_month = ? and original_tenant_id = ? and invoice_number = ? and type = ?", record.BillMonth, record.OriginalTenantID, record.InvoiceNumber, record.Type).First(&tmpCollection).Error
		if err == gorm.ErrRecordNotFound {
			err = c.db.Create(&record).Error
			if err != nil {
				return nil, err
			}

			dRecords = append(dRecords, record)
		}
	}

	return dRecords, nil
}
