/*
 * SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
 * SPDX-License-Identifier: AGPL-3.0-only
 */

package types

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

	"github.com/jackc/pgx/v4"

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

func (h *AdminHandler) optionsHandler(user *auth.User, company *auth.Company, conn *database.Conn, typeSlug string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var head string
		head, r.URL.Path = httplib.ShiftPath(r.URL.Path)

		switch head {
		case "":
			switch r.Method {
			case http.MethodGet:
				serveOptionIndex(w, r, user, company, conn, typeSlug)
			case http.MethodPost:
				addOption(w, r, user, company, conn, typeSlug)
			default:
				httplib.MethodNotAllowed(w, r, http.MethodGet, http.MethodPost)
			}
		case "new":
			switch r.Method {
			case http.MethodGet:
				f, err := newOptionForm(r.Context(), company, conn, typeSlug)
				if err != nil {
					panic(err)
				}
				f.MustRender(w, r, user, company)
			default:
				httplib.MethodNotAllowed(w, r, http.MethodGet)
			}
		case "order":
			switch r.Method {
			case http.MethodPost:
				orderOptions(w, r, user, company, conn, typeSlug)
			default:
				httplib.MethodNotAllowed(w, r, http.MethodPost)
			}
		default:
			id, err := strconv.Atoi(head)
			if err != nil {
				http.NotFound(w, r)
				return
			}
			f, err := newOptionForm(r.Context(), company, conn, typeSlug)
			if err != nil {
				panic(err)
			}
			if err := f.FillFromDatabase(r.Context(), conn, id); err != nil {
				if database.ErrorIsNotFound(err) {
					http.NotFound(w, r)
					return
				}
				panic(err)
			}
			h.optionHandler(user, company, conn, f).ServeHTTP(w, r)
		}
	})
}

func (h *AdminHandler) optionHandler(user *auth.User, company *auth.Company, conn *database.Conn, f *optionForm) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var head string
		head, r.URL.Path = httplib.ShiftPath(r.URL.Path)

		switch head {
		case "":
			switch r.Method {
			case http.MethodGet:
				f.MustRender(w, r, user, company)
			case http.MethodPut:
				editOption(w, r, user, company, conn, f)
			case http.MethodDelete:
				deleteOption(w, r, user, conn, f.TypeSlug, f.ID)
			default:
				httplib.MethodNotAllowed(w, r, http.MethodGet, http.MethodPut, http.MethodDelete)
			}
		default:
			http.NotFound(w, r)
		}
	})
}

func serveOptionIndex(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, conn *database.Conn, typeSlug string) {
	options, err := collectOptionEntries(r.Context(), conn, typeSlug)
	if err != nil {
		panic(err)
	}
	page := &optionIndex{
		TypeSlug: typeSlug,
		Options:  options,
	}
	page.MustRender(w, r, user, company)
}

func collectOptionEntries(ctx context.Context, conn *database.Conn, typeSlug string) ([]*optionEntry, error) {
	rows, err := conn.Query(ctx, `
		select campsite_type_option_id
		     , '/admin/campsites/types/' || campsite_type.slug || '/options/' || campsite_type_option_id
		     , option.name
		from campsite_type_option as option
		    join campsite_type using (campsite_type_id)
		where campsite_type.slug = $1
		order by option.position, option.name
	`, typeSlug)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var options []*optionEntry
	for rows.Next() {
		option := &optionEntry{}
		if err = rows.Scan(&option.ID, &option.URL, &option.Name); err != nil {
			return nil, err
		}
		options = append(options, option)
	}

	return options, nil
}

type optionEntry struct {
	ID   int
	URL  string
	Name string
}

type optionIndex struct {
	TypeSlug string
	Options  []*optionEntry
}

func (page *optionIndex) MustRender(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company) {
	template.MustRenderAdmin(w, r, user, company, "campsite/type/option/index.gohtml", page)
}

func addOption(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, conn *database.Conn, typeSlug string) {
	f, err := newOptionForm(r.Context(), company, conn, typeSlug)
	if err != nil {
		panic(err)
	}
	processOptionForm(w, r, user, company, conn, f, func(ctx context.Context, tx *database.Tx) error {
		var err error
		f.ID, err = tx.AddCampsiteTypeOption(ctx, typeSlug, f.Name[f.DefaultLang].Val, f.Min.Int(), f.Max.Int(), f.PerNight.Checked)
		if err != nil {
			return err
		}
		if err := translateOptions(ctx, tx, company, f); err != nil {
			return err
		}
		return setOptionPrices(ctx, tx, f.ID, f.Prices)
	})
}

func translateOptions(ctx context.Context, tx *database.Tx, company *auth.Company, f *optionForm) error {
	for lang := range company.Locales {
		l := lang.String()
		if l == f.DefaultLang {
			continue
		}
		if err := tx.TranslateCampsiteTypeOption(ctx, f.ID, lang, f.Name[l].Val); err != nil {
			return err
		}
	}
	return nil
}

func editOption(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, conn *database.Conn, f *optionForm) {
	processOptionForm(w, r, user, company, conn, f, func(ctx context.Context, tx *database.Tx) error {
		if _, err := tx.EditCampsiteTypeOption(ctx, f.ID, f.Name[f.DefaultLang].Val, f.Min.Int(), f.Max.Int(), f.PerNight.Checked); err != nil {
			return err
		}
		if err := translateOptions(ctx, tx, company, f); err != nil {
			return err
		}
		return setOptionPrices(ctx, tx, f.ID, f.Prices)
	})
}

func deleteOption(w http.ResponseWriter, r *http.Request, user *auth.User, conn *database.Conn, typeSlug string, id int) {
	if err := user.VerifyCSRFToken(r); err != nil {
		http.Error(w, err.Error(), http.StatusForbidden)
		return
	}
	if err := conn.RemoveCampsiteTypeOption(r.Context(), id); err != nil {
		panic(err)
	}
	httplib.Redirect(w, r, "/admin/campsites/types/"+typeSlug+"/options", http.StatusSeeOther)
}

func processOptionForm(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, conn *database.Conn, f *optionForm, act func(ctx context.Context, tx *database.Tx) error) {
	if ok, err := form.Handle(f, w, r, user); err != nil {
		return
	} else if !ok {
		f.MustRender(w, r, user, company)
		return
	}

	tx := conn.MustBegin(r.Context())
	if err := act(r.Context(), tx); err == nil {
		if err := tx.Commit(r.Context()); err != nil {
			panic(err)
		}
	} else {
		if err := tx.Rollback(r.Context()); err != nil {
			panic(err)
		}
		panic(err)
	}
	httplib.Redirect(w, r, "/admin/campsites/types/"+f.TypeSlug+"/options", http.StatusSeeOther)
}

func setOptionPrices(ctx context.Context, tx *database.Tx, id int, prices map[int]*optionPriceForm) error {
	for seasonID, p := range prices {
		if err := tx.SetCampsiteTypeOptionCost(ctx, id, seasonID, p.Price.Val); err != nil {
			return err
		}
	}
	return nil
}

type optionForm struct {
	DefaultLang string
	ID          int
	TypeSlug    string
	Name        form.I18nInput
	Min         *form.Input
	Max         *form.Input
	PerNight    *form.Checkbox
	Prices      map[int]*optionPriceForm
}

type optionPriceForm struct {
	SeasonName string
	Price      *form.Input
}

func newOptionForm(ctx context.Context, company *auth.Company, conn *database.Conn, typeSlug string) (*optionForm, error) {
	f := &optionForm{
		DefaultLang: company.DefaultLanguage.String(),
		TypeSlug:    typeSlug,
		Name:        form.NewI18nInput(company.Locales, "name"),
		Min: &form.Input{
			Name: "min",
			Val:  "0",
		},
		Max: &form.Input{
			Name: "max",
			Val:  "1",
		},
		PerNight: &form.Checkbox{
			Name:    "per_night",
			Checked: true,
		},
	}

	rows, err := conn.Query(ctx, "select season_id, name from season where active and company_id = $1", company.ID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	f.Prices = make(map[int]*optionPriceForm)
	for rows.Next() {
		var id int
		var name string
		if err = rows.Scan(&id, &name); err != nil {
			return nil, err
		}
		f.Prices[id] = &optionPriceForm{
			SeasonName: name,
			Price: &form.Input{
				Name: fmt.Sprintf("season.%d.price", id),
				Val:  "0",
			},
		}
	}

	return f, nil
}

func (f *optionForm) FillFromDatabase(ctx context.Context, conn *database.Conn, id int) error {
	f.ID = id
	var name database.RecordArray
	row := conn.QueryRow(ctx, `
		select option.name
		     , lower(range)::text
		     , (upper(range) - 1)::text
		     , per_night
		     , array_agg((lang_tag, i18n.name))
		from campsite_type_option as option
        left join campsite_type_option_i18n as i18n using (campsite_type_option_id)
		where campsite_type_option_id = $1
		group by option.name
		       , per_night
		       , range
	`, pgx.QueryResultFormats{pgx.BinaryFormatCode}, id)
	if err := row.Scan(&f.Name[f.DefaultLang].Val, &f.Min.Val, &f.Max.Val, &f.PerNight.Checked, &name); err != nil {
		return err
	}
	if err := f.Name.FillArray(name); err != nil {
		return err
	}

	rows, err := conn.Query(ctx, `
		select season_id
		     , to_price(cost)
		from campsite_type_option
		join campsite_type_option_cost using (campsite_type_option_id)
		where campsite_type_option_id = $1
	`, id)
	if err != nil {
		return err
	}
	defer rows.Close()

	for rows.Next() {
		var seasonID int
		var pricePerNight string
		if err := rows.Scan(&seasonID, &pricePerNight); err != nil {
			return err
		}
		if p, ok := f.Prices[seasonID]; ok {
			p.Price.Val = pricePerNight
		}
	}
	return rows.Err()
}

func (f *optionForm) Parse(r *http.Request) error {
	if err := r.ParseForm(); err != nil {
		return err
	}
	f.Name.FillValue(r)
	f.Min.FillValue(r)
	f.Max.FillValue(r)
	f.PerNight.FillValue(r)
	for _, p := range f.Prices {
		p.Price.FillValue(r)
	}
	return nil
}

func (f *optionForm) Valid(l *locale.Locale) bool {
	v := form.NewValidator(l)
	if v.CheckRequired(f.Name[f.DefaultLang], l.GettextNoop("Name can not be empty.")) {
		v.CheckMinLength(f.Name[f.DefaultLang], 1, l.GettextNoop("Name must have at least one letter."))
	}
	minValidInt := false
	if v.CheckRequired(f.Min, l.GettextNoop("Minimum can not be empty.")) {
		if v.CheckValidInteger(f.Min, l.GettextNoop("Minimum must be an integer number.")) {
			minValidInt = true
			v.CheckMinInteger(f.Min, 0, l.GettextNoop("Minimum must be zero or greater."))
		}
	}
	if v.CheckRequired(f.Max, l.GettextNoop("Maximum can not be empty.")) {
		if v.CheckValidInteger(f.Min, l.GettextNoop("Maximum must be an integer number.")) && minValidInt {
			min, _ := strconv.Atoi(f.Min.Val)
			v.CheckMinInteger(f.Min, min, l.GettextNoop("Maximum must be equal or greater than minimum."))
		}
	}
	for _, p := range f.Prices {
		if v.CheckRequired(p.Price, l.GettextNoop("Price can not be empty.")) {
			if v.CheckValidDecimal(p.Price, l.GettextNoop("Price must be a decimal number.")) {
				v.CheckMinDecimal(p.Price, 0.0, l.GettextNoop("Price must be zero or greater."))
			}
		}
	}
	return v.AllOK
}

func (f *optionForm) MustRender(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company) {
	template.MustRenderAdmin(w, r, user, company, "campsite/type/option/form.gohtml", f)
}

func orderOptions(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, conn *database.Conn, typeSlug string) {
	if err := r.ParseForm(); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	if err := user.VerifyCSRFToken(r); err != nil {
		http.Error(w, err.Error(), http.StatusForbidden)
		return
	}
	input := r.PostForm["option_id"]
	if len(input) > 0 {
		var ids []int
		for _, s := range input {
			if id, err := strconv.Atoi(s); err == nil {
				ids = append(ids, id)
			} else {
				http.Error(w, err.Error(), http.StatusUnprocessableEntity)
				return
			}
		}
		if err := conn.OrderCampsiteTypeOptions(r.Context(), ids); err != nil {
			panic(err)
		}
	}
	serveOptionIndex(w, r, user, company, conn, typeSlug)
}
