package system

import (
	"context"
	"strconv"

	"kra/internal/biz/system"
	"kra/internal/data/model"
	"kra/internal/data/query"

	"gorm.io/gorm"
)

type versionRepo struct {
	db *gorm.DB
}

// NewVersionRepo 创建版本仓储
func NewVersionRepo(db *gorm.DB) system.VersionRepo {
	return &versionRepo{db: db}
}

func (r *versionRepo) Create(ctx context.Context, version *system.SysVersion) error {
	m := &model.SysVersion{
		VersionName: version.VersionName,
		VersionCode: version.VersionCode,
		Description: version.Description,
		VersionData: version.VersionData,
	}
	return query.SysVersion.WithContext(ctx).Create(m)
}

func (r *versionRepo) Delete(ctx context.Context, id string) error {
	idInt, _ := strconv.ParseInt(id, 10, 64)
	_, err := query.SysVersion.WithContext(ctx).Where(query.SysVersion.ID.Eq(idInt)).Delete()
	return err
}

func (r *versionRepo) DeleteByIds(ctx context.Context, ids []string) error {
	idList := make([]int64, len(ids))
	for i, id := range ids {
		idList[i], _ = strconv.ParseInt(id, 10, 64)
	}
	_, err := query.SysVersion.WithContext(ctx).Where(query.SysVersion.ID.In(idList...)).Delete()
	return err
}

func (r *versionRepo) GetById(ctx context.Context, id string) (*system.SysVersion, error) {
	idInt, _ := strconv.ParseInt(id, 10, 64)
	m, err := query.SysVersion.WithContext(ctx).Where(query.SysVersion.ID.Eq(idInt)).First()
	if err != nil {
		return nil, err
	}
	return toBizVersion(m), nil
}

func (r *versionRepo) GetList(ctx context.Context, req *system.VersionSearchReq) ([]*system.SysVersion, int64, error) {
	q := query.SysVersion.WithContext(ctx).Order(query.SysVersion.CreatedAt.Desc())

	// 条件搜索
	if len(req.CreatedAtRange) == 2 {
		q = q.Where(query.SysVersion.CreatedAt.Between(req.CreatedAtRange[0], req.CreatedAtRange[1]))
	}
	if req.VersionName != nil && *req.VersionName != "" {
		q = q.Where(query.SysVersion.VersionName.Like("%" + *req.VersionName + "%"))
	}
	if req.VersionCode != nil && *req.VersionCode != "" {
		q = q.Where(query.SysVersion.VersionCode.Eq(*req.VersionCode))
	}

	total, err := q.Count()
	if err != nil {
		return nil, 0, err
	}

	if req.PageSize > 0 {
		offset := req.PageSize * (req.Page - 1)
		q = q.Limit(req.PageSize).Offset(offset)
	}

	list, err := q.Find()
	if err != nil {
		return nil, 0, err
	}

	result := make([]*system.SysVersion, len(list))
	for i, m := range list {
		result[i] = toBizVersion(m)
	}
	return result, total, nil
}

func toBizVersion(m *model.SysVersion) *system.SysVersion {
	return &system.SysVersion{
		ID:          m.ID,
		VersionName: m.VersionName,
		VersionCode: m.VersionCode,
		Description: m.Description,
		VersionData: m.VersionData,
		CreatedAt:   m.CreatedAt,
		UpdatedAt:   m.UpdatedAt,
	}
}
