package logic

import (
	"context"

	"github.com/zeromicro/go-zero/core/logx"
	"sundynix-micro-go/app/file/model"
	"sundynix-micro-go/app/file/rpc/file"
	"sundynix-micro-go/app/file/rpc/internal/svc"
)

type GetStorageConfigListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetStorageConfigListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetStorageConfigListLogic {
	return &GetStorageConfigListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetStorageConfigListLogic) GetStorageConfigList(in *file.StorageConfigListReq) (*file.StorageConfigListResp, error) {
	var list []model.StorageConfig
	var total int64

	db := l.svcCtx.DB.Model(&model.StorageConfig{})
	if in.Type != "" {
		db = db.Where("type = ?", in.Type)
	}
	if in.Name != "" {
		db = db.Where("name LIKE ?", "%"+in.Name+"%")
	}

	db.Count(&total)

	if in.Current > 0 && in.PageSize > 0 {
		offset := (in.Current - 1) * in.PageSize
		db = db.Offset(int(offset)).Limit(int(in.PageSize))
	}

	if err := db.Find(&list).Error; err != nil {
		return nil, err
	}

	var respList []*file.StorageConfigInfo
	for _, item := range list {
		respList = append(respList, &file.StorageConfigInfo{
			Id:              item.ID,
			Type:            item.Type,
			Name:            item.Name,
			Endpoint:        item.Endpoint,
			AccessKeyId:     item.AccessKeyId,
			AccessKeySecret: item.AccessKeySecret,
			BucketName:      item.BucketName,
			BucketUrl:       item.BucketUrl,
			Region:          item.Region,
			IsDefault:       int32(item.IsDefault),
			Status:          int32(item.Status),
			Remark:          item.Remark,
		})
	}

	return &file.StorageConfigListResp{
		List:  respList,
		Total: total,
	}, nil
}
