package mysql

import (
	"context"
	"errors"
	"time"

	"gorm.io/gorm"

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

type ForcesPresentRepository struct {
	db *gorm.DB
}

func NewForcesPresentRepository(db *gorm.DB) *ForcesPresentRepository {
	return &ForcesPresentRepository{db: db}
}

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

func (r *ForcesPresentRepository) Update(ctx context.Context, row *forces_present.ForcesPresent) error {
	return r.db.WithContext(ctx).Save(row).Error
}

func (r *ForcesPresentRepository) Delete(ctx context.Context, id []byte, deletedBy []byte) error {
	if err := ensureNoReferenceBeforeDelete(ctx, r.db, "forces_present", 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(&forces_present.ForcesPresent{}).
		Where("id = ? AND deleted_at IS NULL", id).
		Updates(updates).Error)
}

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

	base := r.db.WithContext(ctx).Model(&forces_present.ForcesPresent{}).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("forces_present", "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
}
