package api

import (
	"errors"
	"fmt"
	"net/http"
	"time"

	"party.at/party/cmd/party/common"
	"party.at/party/internal/data"
	"party.at/party/internal/validator"
)

func (api *Api) ListIssues(w http.ResponseWriter, r *http.Request) {
	var input struct {
		Title string
		data.Filters
	}

	v := validator.New()
	qs := r.URL.Query()

	input.Title = common.ReadString(qs, "title", "")
	input.Filters.Page = common.ReadInt(qs, "page", 1, v)
	input.Filters.PageSize = common.ReadInt(qs, "page_size", 20, v)
	input.Filters.Sort = common.ReadString(qs, "sort", "id")
	input.Filters.SortSafelist = []string{"id", "-id", "title", "-title", "description", "-description"}

	if data.ValidateFilters(v, input.Filters); !v.Valid() {
		api.errorResponse(w, r, data.ErrValidationFailed.(*data.Error).WithDetails(v.Errors))
		return
	}

	issues, metadata, err := api.App.FetchIssues(input.Title, input.Filters, common.GetUser(r))
	if err != nil {
		api.ServerErrorResponse(w, r, err)
		return
	}

	if err = common.WriteJSON(w, http.StatusOK, common.Envelope{"issues": issues, "metadata": metadata}, nil); err != nil {
		api.ServerErrorResponse(w, r, err)
	}
}

func (api *Api) CreateIssue(w http.ResponseWriter, r *http.Request) {
	var input struct {
		Title       string    `json:"title"`
		Description string    `json:"description"`
		StartTime   time.Time `json:"start_time"`
		EndTime     time.Time `json:"end_time"`
		Options     []string  `json:"options"`
	}

	if err := common.ReadJSON(w, r, &input); err != nil {
		api.errorResponse(w, r, data.ErrBadRequest)
		return
	}

	issue, options, err := api.App.CreateIssue(input.Title, input.Description, input.StartTime, input.EndTime, input.Options)
	if err != nil {
		api.errorResponse(w, r, err)
		return
	}

	headers := make(http.Header)
	headers.Set("Location", fmt.Sprintf("/v1/issues/%d", issue.ID))
	if err = common.WriteJSON(w, http.StatusCreated, common.Envelope{"issue": issue, "options": options}, headers); err != nil {
		api.ServerErrorResponse(w, r, err)
	}
}

func (api *Api) ReadIssue(w http.ResponseWriter, r *http.Request) {
	id, err := common.ReadIDParam(r)
	if err != nil {
		api.errorResponse(w, r, data.ErrRecordNotFound)
		return
	}

	result, err := api.App.GetIssue(id, common.GetUser(r))
	if err != nil {
		if errors.Is(err, data.ErrRecordNotFound) {
			api.errorResponse(w, r, data.ErrRecordNotFound)
		} else {
			api.ServerErrorResponse(w, r, err)
		}
		return
	}

	if err = common.WriteJSON(w, http.StatusOK, common.Envelope{"issue": result.IssueDetail, "options": result.Options}, nil); err != nil {
		api.ServerErrorResponse(w, r, err)
	}
}

func (api *Api) UpdateIssue(w http.ResponseWriter, r *http.Request) {
	id, err := common.ReadIDParam(r)
	if err != nil {
		api.errorResponse(w, r, data.ErrRecordNotFound)
		return
	}

	var input struct {
		Title       *string    `json:"title"`
		Description *string    `json:"description"`
		StartTime   *time.Time `json:"start_time"`
		EndTime     *time.Time `json:"end_time"`
	}

	if err = common.ReadJSON(w, r, &input); err != nil {
		api.errorResponse(w, r, data.ErrBadRequest)
		return
	}

	issue, err := api.App.UpdateIssue(id, input.Title, input.Description, input.StartTime, input.EndTime)
	if err != nil {
		api.errorResponse(w, r, err)
		return
	}

	if err = common.WriteJSON(w, http.StatusOK, common.Envelope{"issue": issue}, nil); err != nil {
		api.ServerErrorResponse(w, r, err)
	}
}

func (api *Api) DeleteIssue(w http.ResponseWriter, r *http.Request) {
	id, err := common.ReadIDParam(r)
	if err != nil {
		api.errorResponse(w, r, data.ErrRecordNotFound)
		return
	}

	if err = api.App.DeleteIssue(id); err != nil {
		if errors.Is(err, data.ErrRecordNotFound) {
			api.errorResponse(w, r, data.ErrRecordNotFound)
		} else {
			api.ServerErrorResponse(w, r, err)
		}
		return
	}

	if err = common.WriteJSON(w, http.StatusOK, common.Envelope{"message": "issue successfully deleted"}, nil); err != nil {
		api.ServerErrorResponse(w, r, err)
	}
}

func (api *Api) ReadIssuePubKey(w http.ResponseWriter, r *http.Request) {
	id, err := common.ReadIDParam(r)
	if err != nil {
		api.errorResponse(w, r, data.ErrRecordNotFound)
		return
	}

	pubKey, err := api.App.GetIssuePublicKey(id)
	if err != nil {
		if errors.Is(err, data.ErrRecordNotFound) {
			api.errorResponse(w, r, data.ErrRecordNotFound)
		} else {
			api.ServerErrorResponse(w, r, err)
		}
		return
	}

	if err = common.WriteJSON(w, http.StatusOK, common.Envelope{"public_key": pubKey}, nil); err != nil {
		api.ServerErrorResponse(w, r, err)
	}
}

func (api *Api) BlindSignIssueVote(w http.ResponseWriter, r *http.Request) {
	id, err := common.ReadIDParam(r)
	if err != nil {
		api.errorResponse(w, r, data.ErrRecordNotFound)
		return
	}

	var input struct {
		BlindedVote []byte `json:"blinded_vote"`
	}
	if err = common.ReadJSON(w, r, &input); err != nil {
		api.errorResponse(w, r, data.ErrBadRequest)
		return
	}

	signed, err := api.App.BlindSign(id, input.BlindedVote, common.GetUser(r))
	if err != nil {
		api.errorResponse(w, r, err)
		return
	}

	if err = common.WriteJSON(w, http.StatusOK, common.Envelope{"signed": signed}, nil); err != nil {
		api.ServerErrorResponse(w, r, err)
	}
}
