package model

import (
	"context"
	"gorm.io/gorm"
	"gxt-file-server/app/errors"
	"gxt-file-server/app/model/entity"
	"gxt-file-server/app/schema"
)

// NewFileHistory 创建demo存储实例
func NewFileHistory(db *gorm.DB) *FileHistory {
	return &FileHistory{db}
}

// FileHistory demo存储
type FileHistory struct {
	db *gorm.DB
}

func (a *FileHistory) getQueryOption(opts ...schema.FileHistoryQueryOptions) schema.FileHistoryQueryOptions {
	var opt schema.FileHistoryQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}
	return opt
}

// Query 查询数据
func (a *FileHistory) Query(ctx context.Context, params schema.FileHistoryQueryParam, opts ...schema.FileHistoryQueryOptions) (*schema.FileHistoryQueryResult, error) {
	db := entity.GetFileHistoryDB(ctx, a.db)
	if v := params.FileName; v != "" {
		db = db.Where("file_name = ?", v)
	}
	if v := params.Hash; v != "" {
		db = db.Where("hash = ?", v)
	}
	if v := params.FileHash; v != "" {
		db = db.Where("file_hash = ?", v)
	}
	if v := params.IsPersistent; v > 0 {
		db = db.Where("is_persistent = ?", v)
	}
	db = db.Order("id DESC")

	opt := a.getQueryOption(opts...)
	var list entity.FileHistories
	pr, err := WrapPageQuery(ctx, db, opt.PageParam, &list)
	if err != nil {
		return nil, errors.ErrDBServerInternalError
	}
	qr := &schema.FileHistoryQueryResult{
		PageResult: pr,
		Data:       list.ToSchemaFileHistories(),
	}

	return qr, nil
}

// Get 查询指定数据
func (a *FileHistory) Get(ctx context.Context, recordID string, opts ...schema.FileHistoryQueryOptions) (*schema.FileHistory, error) {
	db := entity.GetFileHistoryDB(ctx, a.db).Where("record_id=?", recordID)
	var item entity.FileHistory
	ok, err := FindOne(ctx, db, &item)
	if err != nil {
		return nil, errors.ErrDBServerInternalError
	} else if !ok {
		return nil, nil
	}

	return item.ToSchemaFileHistory(), nil
}

// Create 创建数据
func (a *FileHistory) Create(ctx context.Context, item schema.FileHistory) error {
	demo := entity.SchemaFileHistory(item).ToFileHistory()
	result := entity.GetFileHistoryDB(ctx, a.db).Create(demo)
	if err := result.Error; err != nil {
		return errors.ErrDBServerInternalError
	}
	return nil
}

// Delete 删除数据
func (a *FileHistory) Delete(ctx context.Context, recordId string) error {
	result := entity.GetFileHistoryDB(ctx, a.db).Where("record_id =?", recordId).Unscoped().Delete(entity.FileHistory{})
	if err := result.Error; err != nil {
		return errors.ErrDBServerInternalError
	}
	return nil
}

// Update 更新数据
func (a *FileHistory) Update(ctx context.Context, recordID string, item schema.FileHistory) error {
	demo := entity.SchemaFileHistory(item).ToFileHistory()
	result := entity.GetFileHistoryDB(ctx, a.db).Where("record_id=?", recordID).Omit("record_id", "creator").Updates(demo)
	if err := result.Error; err != nil {
		return errors.ErrDBServerInternalError
	}
	return nil
}
