package authorization

import (
	"context"
	"errors"

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

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

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

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

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

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

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

	// 4. 构建响应
	resp = &types.GetAuthorizationDocumentResp{
		DocumentId: authDoc.Id,
		UserId:     authDoc.UserId,
		OrderId:    authDoc.OrderId,
		QueryId:    authDoc.QueryId,
		FileName:   authDoc.FileName,
		FileUrl:    fullFileURL,
		FileSize:   authDoc.FileSize,
		FileType:   authDoc.FileType,
		Status:     authDoc.Status,
		CreateTime: authDoc.CreateTime.Format("2006-01-02 15:04:05"),
	}

	return resp, nil
}
