package invoice

import (
	"io"

	"code.gitea.io/sdk/gitea"
	"git.schreifuchs.ch/lou-taylor/accounting/pkg/invoice/issue"
	"git.schreifuchs.ch/lou-taylor/accounting/pkg/invoice/model"
	"git.schreifuchs.ch/lou-taylor/accounting/pkg/invoice/report"
)

func (s *Service) Generate(creditor model.Entity, deptor *model.Entity, rate float64, repos []Repo, config *Options) (document io.ReadCloser, r *report.Report, err error) {
	if config == nil {
		config = &DefaultOptions
	}
	var is []*gitea.Issue
	for _, repo := range repos {
		iss, _, err := s.gitea.ListRepoIssues(
			repo.Owner,
			repo.Repo,
			gitea.ListIssueOption{
				ListOptions: gitea.ListOptions{Page: 0, PageSize: 99999},
				Since:       config.Since,
				Before:      config.Before,
				State:       config.IssueState,
			},
		)
		if err != nil {
			return nil, nil, err
		}

		is = append(is, iss...)
	}

	is = filter(is, config.IssueFilter)
	issues := issue.FromGiteas(is, config.Mindur)
	r = report.New(
		issues,
		creditor,
		deptor,
		rate,
	)
	html, err := r.ToHTML()
	if err != nil {
		return document, r, err
	}

	document, err = s.pdf.HtmlToPdf(html)
	return document, r, err
}

func filter[T any](slice []T, ok func(T) bool) []T {
	out := make([]T, 0, len(slice))

	for _, item := range slice {
		if ok(item) {
			out = append(out, item)
		}
	}

	return out
}
