package repository

import (
	"context"

	"apskel-pos-be/internal/entities"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

type ProductVariantRepository interface {
	Create(ctx context.Context, variant *entities.ProductVariant) error
	GetByID(ctx context.Context, id uuid.UUID) (*entities.ProductVariant, error)
	GetByProductID(ctx context.Context, productID uuid.UUID) ([]*entities.ProductVariant, error)
	GetByProductAndName(ctx context.Context, productID uuid.UUID, name string) (*entities.ProductVariant, error)
	Update(ctx context.Context, variant *entities.ProductVariant) error
	Delete(ctx context.Context, id uuid.UUID) error
	ExistsByName(ctx context.Context, productID uuid.UUID, name string, excludeID *uuid.UUID) (bool, error)
}

type ProductVariantRepositoryImpl struct {
	db *gorm.DB
}

func NewProductVariantRepositoryImpl(db *gorm.DB) *ProductVariantRepositoryImpl {
	return &ProductVariantRepositoryImpl{
		db: db,
	}
}

func (r *ProductVariantRepositoryImpl) Create(ctx context.Context, variant *entities.ProductVariant) error {
	return r.db.WithContext(ctx).Create(variant).Error
}

func (r *ProductVariantRepositoryImpl) GetByID(ctx context.Context, id uuid.UUID) (*entities.ProductVariant, error) {
	var variant entities.ProductVariant
	err := r.db.WithContext(ctx).First(&variant, "id = ?", id).Error
	if err != nil {
		return nil, err
	}
	return &variant, nil
}

func (r *ProductVariantRepositoryImpl) GetByProductID(ctx context.Context, productID uuid.UUID) ([]*entities.ProductVariant, error) {
	var variants []*entities.ProductVariant
	err := r.db.WithContext(ctx).Where("product_id = ?", productID).Find(&variants).Error
	return variants, err
}

func (r *ProductVariantRepositoryImpl) GetByProductAndName(ctx context.Context, productID uuid.UUID, name string) (*entities.ProductVariant, error) {
	var variant entities.ProductVariant
	err := r.db.WithContext(ctx).Where("product_id = ? AND name = ?", productID, name).First(&variant).Error
	if err != nil {
		return nil, err
	}
	return &variant, nil
}

func (r *ProductVariantRepositoryImpl) Update(ctx context.Context, variant *entities.ProductVariant) error {
	return r.db.WithContext(ctx).Save(variant).Error
}

func (r *ProductVariantRepositoryImpl) Delete(ctx context.Context, id uuid.UUID) error {
	return r.db.WithContext(ctx).Delete(&entities.ProductVariant{}, "id = ?", id).Error
}

func (r *ProductVariantRepositoryImpl) ExistsByName(ctx context.Context, productID uuid.UUID, name string, excludeID *uuid.UUID) (bool, error) {
	var count int64
	query := r.db.WithContext(ctx).Model(&entities.ProductVariant{}).Where("product_id = ? AND name = ?", productID, name)

	if excludeID != nil {
		query = query.Where("id != ?", *excludeID)
	}

	err := query.Count(&count).Error
	return count > 0, err
}
