package system

import (
	"context"
	"time"

	"kra/internal/biz"
	"kra/pkg/database/pagination"

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

type parameterRepo struct{ data Provider }

func NewParameterRepo(data Provider) biz.ParameterRepo { return &parameterRepo{data: data} }

type parameterPO struct {
	ID        uint `gorm:"primaryKey"`
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt gorm.DeletedAt `gorm:"index"`
	Name      string
	Key       string
	Value     string
	Desc      string
}

func (parameterPO) TableName() string { return "sys_params" }

func (r *parameterRepo) CreateParameter(ctx context.Context, v *biz.SystemParameter) error {
	po := parameterPO{ID: v.ID, CreatedAt: v.CreatedAt, UpdatedAt: v.UpdatedAt, Name: v.Name, Key: v.Key, Value: v.Value, Desc: v.Desc}
	if err := r.data.DB().WithContext(ctx).Create(&po).Error; err != nil {
		return err
	}
	v.ID, v.CreatedAt, v.UpdatedAt = po.ID, po.CreatedAt, po.UpdatedAt
	return nil
}
func (r *parameterRepo) UpdateParameter(ctx context.Context, v *biz.SystemParameter) error {
	// The compatible update uses a struct, so zero-value optional fields (notably desc)
	// are intentionally ignored rather than clearing an existing value.
	return r.data.DB().WithContext(ctx).Model(&parameterPO{}).Where("id = ?", v.ID).Updates(&parameterPO{ID: v.ID, CreatedAt: v.CreatedAt, UpdatedAt: v.UpdatedAt, Name: v.Name, Key: v.Key, Value: v.Value, Desc: v.Desc}).Error
}
func (r *parameterRepo) DeleteParameters(ctx context.Context, ids []string) error {
	if len(ids) == 1 {
		return r.data.DB().WithContext(ctx).Delete(&parameterPO{}, "id = ?", ids[0]).Error
	}
	return r.data.DB().WithContext(ctx).Delete(&[]parameterPO{}, "id in ?", ids).Error
}
func (r *parameterRepo) FindParameterByID(ctx context.Context, id string) (*biz.SystemParameter, error) {
	var po parameterPO
	if err := r.data.DB().WithContext(ctx).Where("id = ?", id).First(&po).Error; err != nil {
		return nil, err
	}
	return parameterFromPO(po), nil
}
func (r *parameterRepo) FindParameterByKey(ctx context.Context, key string) (*biz.SystemParameter, error) {
	var po parameterPO
	if err := r.data.DB().WithContext(ctx).Where(parameterPO{Key: key}).First(&po).Error; err != nil {
		return nil, err
	}
	return parameterFromPO(po), nil
}
func (r *parameterRepo) ListParameters(ctx context.Context, page, size int, q *biz.SystemParameter) ([]*biz.SystemParameter, int64, error) {
	db := r.data.DB().WithContext(ctx).Model(&parameterPO{})
	if q != nil {
		if q.StartCreatedAt != nil && q.EndCreatedAt != nil {
			db = db.Where("created_at BETWEEN ? AND ?", q.StartCreatedAt, q.EndCreatedAt)
		}
		if q.Name != "" {
			db = db.Where("name LIKE ?", "%"+q.Name+"%")
		}
		if q.Key != "" {
			db = db.Where(clause.Like{Column: clause.Column{Name: "key"}, Value: "%" + q.Key + "%"})
		}
	}
	var total int64
	if err := db.Count(&total).Error; err != nil {
		return nil, 0, err
	}
	var pos []parameterPO
	if err := pagination.Apply(db, page, size, 100).Find(&pos).Error; err != nil {
		return nil, 0, err
	}
	out := make([]*biz.SystemParameter, 0, len(pos))
	for _, po := range pos {
		out = append(out, parameterFromPO(po))
	}
	return out, total, nil
}
