package mysql

import (
	"context"
	"errors"
	"time"

	"gorm.io/gorm"

	"wucher/internal/domain/operation"
)

type HEMSOperationCategoryRepository struct {
	db *gorm.DB
}

func NewHEMSOperationCategoryRepository(db *gorm.DB) *HEMSOperationCategoryRepository {
	return &HEMSOperationCategoryRepository{db: db}
}

func (r *HEMSOperationCategoryRepository) Create(ctx context.Context, row *operation.HEMSOperationCategory) error {
	return r.db.WithContext(ctx).Create(row).Error
}

func (r *HEMSOperationCategoryRepository) Update(ctx context.Context, row *operation.HEMSOperationCategory) error {
	return r.db.WithContext(ctx).
		Model(&operation.HEMSOperationCategory{}).
		Where("id = ? AND deleted_at IS NULL", row.ID).
		Updates(map[string]any{
			"name":       row.Name,
			"type":       row.Type,
			"updated_by": row.UpdatedBy,
			"updated_at": time.Now().UTC(),
		}).Error
}

func (r *HEMSOperationCategoryRepository) Delete(ctx context.Context, id []byte, deletedBy []byte) error {
	now := time.Now().UTC()
	updates := map[string]any{
		"deleted_at": now,
		"deleted_by": deletedBy,
		"updated_by": deletedBy,
		"updated_at": now,
	}
	return r.db.WithContext(ctx).
		Model(&operation.HEMSOperationCategory{}).
		Where("id = ? AND deleted_at IS NULL", id).
		Updates(updates).Error
}

func (r *HEMSOperationCategoryRepository) GetByID(ctx context.Context, id []byte) (*operation.HEMSOperationCategory, error) {
	var row operation.HEMSOperationCategory
	err := r.db.WithContext(ctx).Where("id = ? AND deleted_at IS NULL", id).First(&row).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	return &row, err
}

func (r *HEMSOperationCategoryRepository) List(ctx context.Context, filter string, sort string, limit, offset int) ([]operation.HEMSOperationCategory, int64, error) {
	var rows []operation.HEMSOperationCategory
	var total int64

	base := r.db.WithContext(ctx).Model(&operation.HEMSOperationCategory{}).Where("deleted_at IS NULL")
	if filter != "" {
		like := "%" + filter + "%"
		base = base.Where("name LIKE ? OR type LIKE ?", like, like)
	}

	query := base
	if sort != "" {
		query = query.Order(sort)
	}
	if err := base.Count(&total).Error; err != nil {
		return nil, 0, err
	}
	if limit > 0 {
		query = query.Limit(limit).Offset(offset)
	}
	if err := query.Find(&rows).Error; err != nil {
		return nil, 0, err
	}
	return rows, total, nil
}
