package main

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"
	"time"

	"git.schreifuchs.ch/lou-taylor/accounting/internal/ask"
	"git.schreifuchs.ch/lou-taylor/accounting/pkg/invoice"
	"git.schreifuchs.ch/lou-taylor/accounting/pkg/invoice/model"
)

type invoiceRequest struct {
	Repos             []string
	Creditor          model.Entity
	Debtor            *model.Entity
	MailTo            string
	DurationThreshold time.Duration
	HourlyRate        float64
}

func (i invoiceRequest) GetRepos() (repos []invoice.Repo, err error) {
	for i, repo := range i.Repos {
		parts := strings.Split(repo, "/")
		if len(parts) != 2 {
			err = fmt.Errorf("cannot read body: repo with index %d does not split into 2 parts", i)
			return repos, err
		}
		repos = append(repos, invoice.Repo{
			Owner: parts[0],
			Repo:  parts[1],
		})
	}
	return repos, err
}

func request(arguments []string, _ any) {
	if len(arguments) < 1 {
		fmt.Println("please specify output file")
		return
	}
	q := invoiceRequest{}

	q.Repos = ask.StringSlice("Please list your repositories", 1, -1, 1, -1)
	q.Creditor.Name = ask.String("Creditor Name (first & last name or company)", 1, -1)
	q.Creditor.Contact = ask.String("Creditor Contact (if for company: Contact person)", 1, -1)
	q.Creditor.Address.Country = ask.String("Creditor Country", 1, -1)
	q.Creditor.Address.Place = ask.String("Creditor City", 1, -1)
	q.Creditor.Address.ZIPCode = ask.String("Creditor postcode", 1, -1)
	q.Creditor.Address.Street = ask.String("Creditor Street", 1, -1)
	q.Creditor.Address.Number = ask.String("Creditor house number", 1, -1)
	q.Creditor.IBAN = ask.String("Creditor IBAN like: CH93 0076 2011 6238 5295 7", 26, 26)

	if ask.Boolean("Do you want to specify a debtor", true) {
		q.Debtor = &model.Entity{}
		q.Debtor.Name = ask.String("Debtor Name (first & last name or company)", 1, -1)
		q.Debtor.Contact = ask.String("Debtor Contact (if for company: Contact person)", 1, -1)
		q.Debtor.Address.Country = ask.String("Debtor Country", 1, -1)
		q.Debtor.Address.Place = ask.String("Debtor City", 1, -1)
		q.Debtor.Address.ZIPCode = ask.String("Debtor postcode", 1, -1)
		q.Debtor.Address.Street = ask.String("Debtor Street", 1, -1)
		q.Debtor.Address.Number = ask.String("Debtor Number", 1, -1)
		q.MailTo = ask.String("Debtor mail address (leave empty to omit)", 0, -1)
	}

	q.DurationThreshold = ask.Duration("Minimum duration for a issue to be billed", time.Duration(0), time.Duration(-1))
	q.HourlyRate = ask.Float64("Price per hour in CHF", 0, -1)

	file, err := os.Create(arguments[0])
	if err != nil {
		fmt.Printf("can't open file: %s %v", arguments[0], err)
		return
	}
	defer file.Close()

	json.NewEncoder(file).Encode(&q)
}
