package delivery_address

import (
	"context"
	"gorm.io/gorm"

	"github.com/UpmeshLTD/urus-aio/infrastructure/db/entities"
)

type Repository interface {
	GetByCartID(ctx context.Context, db *gorm.DB, cartID string) (*entities.DeliveryAddress, error)
	GetByCartIDs(ctx context.Context, db *gorm.DB, cartIDs []string) ([]*entities.DeliveryAddress, error)

	Create(ctx context.Context, db *gorm.DB, deliveryAddress *entities.DeliveryAddress) error
	Update(ctx context.Context, db *gorm.DB, cartID string, deliveryAddress map[string]interface{}) error
}

type repositoryImpl struct {
}

func NewRepository() Repository {
	return &repositoryImpl{}
}

func (r *repositoryImpl) Create(ctx context.Context, db *gorm.DB, deliveryAddress *entities.DeliveryAddress) error {
	return db.Create(&deliveryAddress).Error
}

func (r *repositoryImpl) Update(ctx context.Context, db *gorm.DB, cartID string, deliveryAddress map[string]interface{}) error {
	return db.Model(&entities.DeliveryAddress{}).Where("cart_id = ?", cartID).Updates(&deliveryAddress).Error
}

func (r *repositoryImpl) GetByCartID(ctx context.Context, db *gorm.DB, cartID string) (*entities.DeliveryAddress, error) {
	res := &entities.DeliveryAddress{}
	if err := db.Model(&entities.DeliveryAddress{}).Preload("Address.SubLevelLocations").Preload("Address.Country").First(res, "cart_id = ?", cartID).Error; err != nil {
		return nil, err
	}
	return res, nil
}

func (r *repositoryImpl) GetByCartIDs(ctx context.Context, db *gorm.DB, cartIDs []string) ([]*entities.DeliveryAddress, error) {
	var res []*entities.DeliveryAddress
	if err := db.Model(&entities.DeliveryAddress{}).Preload("Address.SubLevelLocations").Preload("Address.Country").Where("cart_id IN ?", cartIDs).Find(&res).Error; err != nil {
		return nil, err
	}
	return res, nil
}
