package authorization

import (
	"context"
	"errors"

	"jnc-server/app/main/api/internal/svc"
	"jnc-server/app/main/api/internal/types"

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

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

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

func (l *DownloadAuthorizationDocumentLogic) DownloadAuthorizationDocument(req *types.DownloadAuthorizationDocumentReq) (resp *types.DownloadAuthorizationDocumentResp, err error) {
	// 1. 从数据库获取授权书信息
	authDoc, err := l.svcCtx.AuthorizationDocumentModel.FindOne(l.ctx, req.DocumentId)
	if err != nil {
		logx.Errorf("获取授权书失败: documentId=%s, error=%v", req.DocumentId, err)
		return nil, err
	}

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

	// 3. 构建完整文件URL
	fullFileURL := l.svcCtx.AuthorizationService.GetFullFileURL(authDoc.FileUrl)

	// 4. 构建响应
	resp = &types.DownloadAuthorizationDocumentResp{
		FileName: authDoc.FileName,
		FileUrl:  fullFileURL,
	}

	return resp, nil
}
