package invoice

import (
	"io"
	"time"

	"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, mindur time.Duration, rate float64, repos []Repo) (document io.ReadCloser, r *report.Report, err error) {
	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:       time.Now().AddDate(0, -1, 0),
				Before:      time.Now(),
				State:       gitea.StateClosed,
			},
		)
		if err != nil {
			return nil, nil, err
		}

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

	is = filter(
		is,
		func(i *gitea.Issue) bool {
			return i.Closed != nil && i.Closed.After(time.Now().AddDate(0, -1, 0))
		},
	)
	issues := issue.FromGiteas(is, 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
}
