package app

import (
	"code.tnxs.net/taxnexus/lib/api/stash/stash_client/stash_pdf"
	"code.tnxs.net/taxnexus/lib/api/stash/stash_models"
)

// StashPDFParams is a param type
type StashPDFParams struct {
	Document   *Document
	Account    *Account
	ObjectType string
	Principal  *User
}

// StashPDF stores a PDF in the stash database
func StashPDF(params StashPDFParams) (*Document, error) {
	sugar.Debugf("app.stashPDF: 📥")
	var title string
	var fileName string
	var description string
	var ref string
	switch params.ObjectType {
	case "account":
		title = "Taxnexus Report for " + params.Account.Name
		fileName = "Taxnexus Report for " + params.Account.Name + ".pdf"
		description = "Account Report generated by render"
		ref = "app.getAccounts"
	case "tax_summary":
		title = "Taxnexus Tax Report for " + params.Account.Name
		fileName = params.Account.Name + " Tax Report.pdf"
		description = "CDTFA Quarterly District Sales and Use Tax for "
		ref = "app.getTaxes"
	}

	stashParams := stash_pdf.NewPostPdfsParamsWithTimeout(getTimeout)
	stashParams.PDFRequest = &stash_models.PDFRequest{
		Data: []*stash_models.NewPDF{
			{
				Description: description,
				Filename:    fileName,
				HTML:        params.Document.HTML,
				ObjectType:  params.Document.SagaType,
				OwnerID:     params.Principal.ID,
				ParentID:    params.Document.ParentID,
				Ref:         ref,
				Title:       title,
			},
		},
	}
	response, err := stashClient.StashPdf.PostPdfs(stashParams, params.Principal.Auth)
	if err != nil {
		sugar.Errorf("app.stashPDF: 💣 ⛔ post PDF to stash error %w", err)
		return nil, err
	}
	var newObj *stash_models.Document
	for _, itm := range response.Payload.Data { // single iteration execution
		newObj = itm
	}
	sugar.Debugf("app.stashPDF: 👍 📤")
	return &Document{
		ID:       newObj.ID,
		Filename: params.Account.Name + fileName,
		SagaType: params.Document.SagaType,
		ParentID: params.Document.ParentID,
		Title:    title + params.Account.Name,
		URI:      newObj.URI,
	}, nil
}
