package authorization

import (
	"context"

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

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

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

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

func (l *GetAuthorizationDocumentByOrderLogic) GetAuthorizationDocumentByOrder(req *types.GetAuthorizationDocumentByOrderReq) (resp *types.GetAuthorizationDocumentByOrderResp, err error) {
	// 1. 根据订单ID查询授权书列表
	authDocs, err := l.svcCtx.AuthorizationDocumentModel.FindByOrderId(l.ctx, req.OrderId)
	if err != nil {
		logx.Errorf("根据订单ID获取授权书失败: orderId=%d, error=%v", req.OrderId, err)
		return nil, err
	}

	// 2. 构建响应列表
	var documents []types.AuthorizationDocumentInfo
	for _, authDoc := range authDocs {
		// 只返回状态为active的授权书
		if authDoc.Status == "active" {
			fullFileURL := l.svcCtx.AuthorizationService.GetFullFileURL(authDoc.FileUrl)
			
			documents = append(documents, types.AuthorizationDocumentInfo{
				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"),
			})
		}
	}

	// 3. 构建响应
	resp = &types.GetAuthorizationDocumentByOrderResp{
		Documents: documents,
	}

	return resp, nil
}
