package invoices

import (
	"time"

	"rmser/internal/domain/invoices"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type pgRepository struct {
	db *gorm.DB
}

func NewRepository(db *gorm.DB) invoices.Repository {
	return &pgRepository{db: db}
}

func (r *pgRepository) GetLastInvoiceDate() (*time.Time, error) {
	var inv invoices.Invoice
	err := r.db.Order("date_incoming DESC").First(&inv).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, err
	}
	return &inv.DateIncoming, nil
}

func (r *pgRepository) SaveInvoices(list []invoices.Invoice) error {
	return r.db.Transaction(func(tx *gorm.DB) error {
		for _, inv := range list {
			if err := tx.Omit("Items").Clauses(clause.OnConflict{
				Columns:   []clause.Column{{Name: "id"}},
				UpdateAll: true,
			}).Create(&inv).Error; err != nil {
				return err
			}
			if err := tx.Where("invoice_id = ?", inv.ID).Delete(&invoices.InvoiceItem{}).Error; err != nil {
				return err
			}
			if len(inv.Items) > 0 {
				if err := tx.Create(&inv.Items).Error; err != nil {
					return err
				}
			}
		}
		return nil
	})
}
