package payment

import (
	"context"
	"fmt"
	"net/http"
	"strconv"
	"strings"

	"dev.tandem.ws/tandem/camper/pkg/auth"
	"dev.tandem.ws/tandem/camper/pkg/database"
	"dev.tandem.ws/tandem/camper/pkg/form"
	"dev.tandem.ws/tandem/camper/pkg/locale"
)

type filterForm struct {
	company       *auth.Company
	PaymentStatus *form.Select
	Reference     *form.Input
	FromDate      *form.Input
	ToDate        *form.Input
	Cursor        *form.Cursor
}

func newFilterForm(ctx context.Context, conn *database.Conn, company *auth.Company, locale *locale.Locale) *filterForm {
	return &filterForm{
		company: company,
		PaymentStatus: &form.Select{
			Name:    "payment_status",
			Options: mustGetPaymentStatusOptions(ctx, conn, locale),
		},
		Reference: &form.Input{
			Name: "reference",
		},
		FromDate: &form.Input{
			Name: "from_date",
		},
		ToDate: &form.Input{
			Name: "to_date",
		},
		Cursor: &form.Cursor{
			Name:    "cursor",
			PerPage: 25,
		},
	}
}

func mustGetPaymentStatusOptions(ctx context.Context, conn *database.Conn, locale *locale.Locale) []*form.Option {
	return form.MustGetOptions(ctx, conn, `
		select payment_status.payment_status
		     , isi18n.name 
		from payment_status
		    join payment_status_i18n isi18n using(payment_status)
		where isi18n.lang_tag = $1
		order by payment_status`, locale.Language)
}

func (f *filterForm) Parse(r *http.Request) error {
	if err := r.ParseForm(); err != nil {
		return err
	}
	f.PaymentStatus.FillValue(r)
	f.Reference.FillValue(r)
	f.FromDate.FillValue(r)
	f.ToDate.FillValue(r)
	f.Cursor.FillValue(r)
	return nil
}

func (f *filterForm) BuildQuery(args []interface{}) (string, []interface{}) {
	var where []string
	appendWhere := func(expression string, value interface{}) {
		args = append(args, value)
		where = append(where, fmt.Sprintf(expression, len(args)))
	}
	maybeAppendWhere := func(expression string, value string, conv func(string) interface{}) {
		if value != "" {
			if conv == nil {
				appendWhere(expression, value)
			} else {
				appendWhere(expression, conv(value))
			}
		}
	}

	appendWhere("payment.company_id = $%d", f.company.ID)
	maybeAppendWhere("payment.payment_status = $%d", f.PaymentStatus.String(), nil)
	maybeAppendWhere("payment.reference like $%d", f.Reference.Val, func(v string) interface{} {
		return "%" + v
	})
	maybeAppendWhere("payment.created_at >= $%d", f.FromDate.Val, nil)
	maybeAppendWhere("payment.created_at <= $%d", f.ToDate.Val, nil)

	if f.Paginated() {
		params := f.Cursor.Params()
		if len(params) == 2 {
			where = append(where, fmt.Sprintf("(payment.created_at, payment_id) < ($%d, $%d)", len(args)+1, len(args)+2))
			args = append(args, params[0])
			args = append(args, params[1])
		}
	}

	return strings.Join(where, ") AND ("), args
}

func (f *filterForm) buildCursor(customers []*paymentEntry) []*paymentEntry {
	return form.BuildCursor(f.Cursor, customers, func(entry *paymentEntry) []string {
		return []string{entry.CreatedAt.Format(database.ISODateTimeFormat), strconv.Itoa(entry.ID)}
	})
}

func (f *filterForm) HasValue() bool {
	return (len(f.PaymentStatus.Selected) > 0 && f.PaymentStatus.Selected[0] != "") ||
		f.Reference.Val != "" ||
		f.FromDate.Val != "" ||
		f.ToDate.Val != ""
}

func (f *filterForm) PerPage() int {
	return f.Cursor.PerPage
}

func (f *filterForm) Paginated() bool {
	return f.Cursor.Pagination
}
