package mysql

import (
	"context"
	"errors"
	"time"

	"gorm.io/gorm"

	"wucher/internal/domain/opc"
	"wucher/internal/shared/pkg/sortkey"
)

type OpcRepository struct {
	db *gorm.DB
}

func NewOpcRepository(db *gorm.DB) *OpcRepository {
	return &OpcRepository{db: db}
}

func (r *OpcRepository) Create(ctx context.Context, o *opc.Opc) error {
	requestedIsActive := o.IsActive
	db := r.db.WithContext(ctx)
	if err := db.Create(o).Error; err != nil {
		return err
	}
	return db.Model(&opc.Opc{}).Where("id = ?", o.ID).UpdateColumn("is_active", requestedIsActive).Error
}

func (r *OpcRepository) Update(ctx context.Context, o *opc.Opc) error {
	return r.db.WithContext(ctx).Save(o).Error
}

func (r *OpcRepository) Delete(ctx context.Context, id []byte, deletedBy []byte) error {
	if err := ensureNoReferenceBeforeDelete(ctx, r.db, "hems_opcs", id); err != nil {
		return err
	}
	now := time.Now().UTC()
	updates := map[string]any{
		"deleted_at": now,
		"deleted_by": deletedBy,
		"updated_by": deletedBy,
	}
	return mapDeleteConstraintError(r.db.WithContext(ctx).
		Model(&opc.Opc{}).
		Where("id = ? AND deleted_at IS NULL", id).
		Updates(updates).Error)
}

func (r *OpcRepository) GetByID(ctx context.Context, id []byte) (*opc.Opc, error) {
	var row opc.Opc
	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 *OpcRepository) List(ctx context.Context, filter, sort string, limit, offset int) ([]opc.Opc, int64, error) {
	var rows []opc.Opc
	var total int64

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

	query := base
	if sort != "" {
		query = query.Order(sort)
	} else {
		for _, clause := range sortkey.ActivePositiveSortClauses("hems_opcs", "is_active", "sortkey", "name", false) {
			query = query.Order(clause)
		}
	}
	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
}
