package authorization

import (
	"context"
	"errors"

	"tydata-server/app/main/api/internal/svc"
	"tydata-server/app/main/api/internal/types"
	"tydata-server/app/main/model"
	"tydata-server/common/globalkey"

	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *DownloadAuthorizationDocumentByNameLogic) DownloadAuthorizationDocumentByName(req *types.DownloadAuthorizationDocumentByNameReq) (resp *types.DownloadAuthorizationDocumentResp, err error) {
	builder := l.svcCtx.AuthorizationDocumentModel.SelectBuilder().
		Where("file_name = ?", req.FileName).
		Where("del_state = ?", globalkey.DelStateNo).
		Limit(1)

	authDocs, err := l.svcCtx.AuthorizationDocumentModel.FindAll(l.ctx, builder, "")
	if err != nil {
		logx.Errorf("根据文件名查询授权书失败: fileName=%s, error=%v", req.FileName, err)
		return nil, err
	}

	if len(authDocs) == 0 {
		logx.Errorf("根据文件名未找到授权书: fileName=%s", req.FileName)
		return nil, model.ErrNotFound
	}
	authDoc := authDocs[0]

	if authDoc.Status != "active" {
		logx.Errorf("授权书状态异常: fileName=%s, status=%s", req.FileName, authDoc.Status)
		return nil, errors.New("授权书不可用")
	}

	filePath := l.svcCtx.AuthorizationService.ResolveFilePath(authDoc.FilePath, authDoc.FileUrl)

	resp = &types.DownloadAuthorizationDocumentResp{
		FileName: authDoc.FileName,
		FilePath: filePath,
	}
	return resp, nil
}
