package mysql

import (
	"context"
	"errors"
	"strings"
	"time"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"

	mastersettings "wucher/internal/domain/master_settings"
)

type MasterSettingsRepository struct {
	db *gorm.DB
}

func NewMasterSettingsRepository(db *gorm.DB) *MasterSettingsRepository {
	return &MasterSettingsRepository{db: db}
}

func (r *MasterSettingsRepository) Create(ctx context.Context, row *mastersettings.MasterSettings) error {
	return r.db.WithContext(ctx).Create(row).Error
}

func (r *MasterSettingsRepository) Update(ctx context.Context, row *mastersettings.MasterSettings) error {
	return r.db.WithContext(ctx).Save(row).Error
}

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

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

	base := r.db.WithContext(ctx).Model(&mastersettings.MasterSettings{}).Where("deleted_at IS NULL")
	if filter != "" {
		like := "%" + filter + "%"
		base = base.Where("company_name LIKE ? OR logo_url LIKE ? OR title LIKE ? OR subtitle LIKE ?", like, 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
}

func (r *MasterSettingsRepository) UpsertSettingValues(ctx context.Context, rows []mastersettings.MasterSettingValue) error {
	if len(rows) == 0 {
		return nil
	}
	now := time.Now().UTC()
	items := make([]mastersettings.MasterSettingValue, 0, len(rows))
	for i := range rows {
		key := strings.TrimSpace(rows[i].SettingKey)
		if key == "" {
			continue
		}
		item := rows[i]
		item.SettingKey = key
		item.UpdatedAt = now
		if item.CreatedAt.IsZero() {
			item.CreatedAt = now
		}
		items = append(items, item)
	}
	if len(items) == 0 {
		return nil
	}
	return r.db.WithContext(ctx).Clauses(clause.OnConflict{
		Columns: []clause.Column{{Name: "setting_key"}},
		DoUpdates: clause.AssignmentColumns([]string{
			"value",
			"is_encrypted",
			"updated_at",
			"updated_by",
		}),
	}).Create(&items).Error
}

func (r *MasterSettingsRepository) GetSettingValuesByKeys(ctx context.Context, keys []string) ([]mastersettings.MasterSettingValue, error) {
	trimmed := make([]string, 0, len(keys))
	for _, key := range keys {
		key = strings.TrimSpace(key)
		if key == "" {
			continue
		}
		trimmed = append(trimmed, key)
	}
	if len(trimmed) == 0 {
		return []mastersettings.MasterSettingValue{}, nil
	}
	var rows []mastersettings.MasterSettingValue
	if err := r.db.WithContext(ctx).
		Where("setting_key IN ?", trimmed).
		Find(&rows).Error; err != nil {
		return nil, err
	}
	return rows, nil
}
