package pdf

import (
	"bytes"
	"fmt"
	"log"
	"os"
	"text/template"

	"github.com/rjNemo/rentease/assets"
	"github.com/rjNemo/rentease/internal/service/booking"
)

type HtmlPdfClient struct{}

func NewPdfClient() (*HtmlPdfClient, error) {
	return &HtmlPdfClient{}, nil
}

func (pc *HtmlPdfClient) BuildInvoice(data booking.Invoice) (string, error) {
	tmpl, err := template.ParseFS(assets.Static, "assets/html/invoice.html")
	if err != nil {
		return "", fmt.Errorf("error parsing template: %v", err)
	}

	// Create a buffer to hold the rendered HTML.
	var buf bytes.Buffer
	if err := tmpl.Execute(&buf, data); err != nil {
		return "", fmt.Errorf("error executing template: %v", err)
	}

	outputPath := fmt.Sprintf("%s.html", data.ID)
	if err := os.WriteFile(outputPath, buf.Bytes(), 0644); err != nil {
		return "", fmt.Errorf("error writing HTML file: %v", err)
	}

	return outputPath, nil
}

func (pc *HtmlPdfClient) BuildReport(report booking.ReportData, period string, month int, year int) (string, error) {
	tmpl, err := template.ParseFS(assets.Static, "assets/html/report.html")
	if err != nil {
		return "", fmt.Errorf("error parsing template: %v", err)
	}

	var buf bytes.Buffer
	if err := tmpl.Execute(&buf, report); err != nil {
		log.Printf("err: %+v\n", err)
		return "", fmt.Errorf("error executing template: %v", err)
	}

	outputPath := fmt.Sprintf("report-%s-%d-%d.html", period, month, year)
	if err := os.WriteFile(outputPath, buf.Bytes(), 0644); err != nil {
		log.Printf("err: %+v\n", err)
		return "", fmt.Errorf("error writing HTML file: %v", err)
	}

	return outputPath, nil
}
