package repository

import (
	"apskel-pos-be/internal/entities"
	"context"
	"fmt"

	"gorm.io/gorm"

	"github.com/google/uuid"
)

type IngredientRepository struct {
	db *gorm.DB
}

func NewIngredientRepository(db *gorm.DB) *IngredientRepository {
	return &IngredientRepository{db: db}
}

func (r *IngredientRepository) Create(ctx context.Context, ingredient *entities.Ingredient) error {
	return r.db.WithContext(ctx).Create(ingredient).Error
}

func (r *IngredientRepository) GetByID(ctx context.Context, id, organizationID uuid.UUID) (*entities.Ingredient, error) {
	var ingredient entities.Ingredient
	err := r.db.WithContext(ctx).Preload("Unit").Where("id = ? AND organization_id = ?", id, organizationID).First(&ingredient).Error
	if err != nil {
		return nil, err
	}
	return &ingredient, nil
}

func (r *IngredientRepository) GetAll(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, page, limit int, search string, isSemiFinished *bool) ([]*entities.Ingredient, int, error) {
	var ingredients []*entities.Ingredient
	var total int64

	query := r.db.WithContext(ctx).Model(&entities.Ingredient{}).Where("organization_id = ?", organizationID)

	if outletID != nil {
		query = query.Where("outlet_id = ?", *outletID)
	}

	if search != "" {
		searchValue := "%" + search + "%"
		query = query.Where("name ILIKE ?", searchValue)
	}

	if isSemiFinished != nil {
		query = query.Where("is_semi_finished = ?", *isSemiFinished)
	}

	// Count total records
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// Get paginated results with Unit preloaded
	offset := (page - 1) * limit
	err := query.Preload("Unit").Order("created_at DESC").Limit(limit).Offset(offset).Find(&ingredients).Error
	if err != nil {
		return nil, 0, err
	}

	return ingredients, int(total), nil
}

func (r *IngredientRepository) Update(ctx context.Context, ingredient *entities.Ingredient) error {
	result := r.db.WithContext(ctx).Where("id = ? AND organization_id = ?", ingredient.ID, ingredient.OrganizationID).Save(ingredient)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return fmt.Errorf("no rows affected")
	}
	return nil
}

func (r *IngredientRepository) UpdateStock(ctx context.Context, id uuid.UUID, quantity float64, organizationID uuid.UUID) error {
	result := r.db.WithContext(ctx).Model(&entities.Ingredient{}).
		Where("id = ? AND organization_id = ?", id, organizationID).
		Update("stock", gorm.Expr("stock + ?", quantity))

	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return fmt.Errorf("no rows affected")
	}
	return nil
}

func (r *IngredientRepository) Delete(ctx context.Context, id, organizationID uuid.UUID) error {
	result := r.db.WithContext(ctx).Where("id = ? AND organization_id = ?", id, organizationID).Delete(&entities.Ingredient{})
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return fmt.Errorf("no rows affected")
	}
	return nil
}
