package lib

import (
	"errors"
	"fmt"
	"path/filepath"
	"strings"

	"github.com/pdfcpu/pdfcpu/pkg/api"
	"github.com/pdfcpu/pdfcpu/pkg/pdfcpu/model"
)

func AppendToPdf(inputPdfFilePath string, inputXmlFilePath string, outputFilePath string) error {
	logger := GetDebugLogger()
	logger.Log(fmt.Sprintf("enter appendToPdf(%s, %s, %s)", inputPdfFilePath, inputXmlFilePath, outputFilePath))
	defer func() {
		logger.Log("leave appendToPdf")
	}()

	if inputPdfFilePath == "" {
		return errors.New("no input pdf file specified")
	}

	if inputXmlFilePath == "" {
		inputXmlFilePath = strings.TrimSuffix(inputPdfFilePath, filepath.Ext(inputPdfFilePath)) + ".xml"
	}

	if outputFilePath == "" {
		outputFilePath = strings.TrimSuffix(
			inputPdfFilePath,
			filepath.Ext(inputPdfFilePath),
		) + "_xml.pdf"
	}

	logger.Log(
		fmt.Sprintf(
			"pdfInput: '%s' xmlInput: '%s' output: '%s'",
			inputPdfFilePath,
			inputXmlFilePath,
			outputFilePath,
		),
	)

	err := api.AddAttachmentsFile(
		inputPdfFilePath,
		outputFilePath,
		[]string{inputXmlFilePath},
		true,
		model.NewDefaultConfiguration(),
	)
	if err != nil {
		return err
	}

	return nil
}
