package scheduler

import (
	"encoding/json"
	"errors"
	"net/http"

	"aigateway.local/core/internal/identity"
	"aigateway.local/core/internal/platform/apiresponse"
)

// PortalHTTPHandler 提供门户工作台定时任务接口:仅管理本人创建的任务。
type PortalHTTPHandler struct {
	service  *Service
	identity *identity.Service
	mux      *http.ServeMux
}

func NewPortalHTTPHandler(service *Service, identityService *identity.Service) *PortalHTTPHandler {
	h := &PortalHTTPHandler{service: service, identity: identityService, mux: http.NewServeMux()}
	h.mux.HandleFunc("GET /api/v1/portal/scheduled-tasks", h.list)
	h.mux.HandleFunc("POST /api/v1/portal/scheduled-tasks", h.create)
	h.mux.HandleFunc("GET /api/v1/portal/scheduled-tasks/{id}", h.get)
	h.mux.HandleFunc("PUT /api/v1/portal/scheduled-tasks/{id}", h.update)
	h.mux.HandleFunc("DELETE /api/v1/portal/scheduled-tasks/{id}", h.delete)
	h.mux.HandleFunc("POST /api/v1/portal/scheduled-tasks/{id}/start", h.start)
	h.mux.HandleFunc("POST /api/v1/portal/scheduled-tasks/{id}/pause", h.pause)
	h.mux.HandleFunc("POST /api/v1/portal/scheduled-tasks/{id}/run", h.runNow)
	h.mux.HandleFunc("GET /api/v1/portal/scheduled-tasks/{id}/runs", h.runs)
	return h
}

func (h *PortalHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.mux.ServeHTTP(w, r) }

func (h *PortalHTTPHandler) account(w http.ResponseWriter, r *http.Request) (identity.Account, bool) {
	account, err := h.identity.Authenticate(r.Context(), identity.KindPortal, r.Header.Get("Authorization"))
	if err != nil {
		apiresponse.Error(w, http.StatusUnauthorized, "登录状态无效或已过期")
		return identity.Account{}, false
	}
	return account, true
}

func (h *PortalHTTPHandler) list(w http.ResponseWriter, r *http.Request) {
	a, ok := h.account(w, r)
	if !ok {
		return
	}
	items, err := h.service.ListByOwner(r.Context(), a.ID)
	if err != nil {
		apiresponse.Error(w, http.StatusServiceUnavailable, "定时任务查询失败")
		return
	}
	apiresponse.OK(w, items)
}

func (h *PortalHTTPHandler) get(w http.ResponseWriter, r *http.Request) {
	a, ok := h.account(w, r)
	if !ok {
		return
	}
	task, err := h.service.GetOwned(r.Context(), a.ID, r.PathValue("id"))
	if err != nil {
		apiresponse.Error(w, http.StatusNotFound, "任务不存在")
		return
	}
	apiresponse.OK(w, task)
}

func (h *PortalHTTPHandler) create(w http.ResponseWriter, r *http.Request) {
	a, ok := h.account(w, r)
	if !ok {
		return
	}
	var input TaskInput
	if err := decodeJSON(w, r, &input); err != nil {
		return
	}
	task, err := h.service.Save(r.Context(), "", input, a.ID)
	if err != nil {
		apiresponse.Error(w, http.StatusBadRequest, err.Error())
		return
	}
	apiresponse.OK(w, task)
}

func (h *PortalHTTPHandler) update(w http.ResponseWriter, r *http.Request) {
	a, ok := h.account(w, r)
	if !ok {
		return
	}
	var input TaskInput
	if err := decodeJSON(w, r, &input); err != nil {
		return
	}
	// 归属校验:仅本人任务可更新。
	if _, err := h.service.GetOwned(r.Context(), a.ID, r.PathValue("id")); err != nil {
		apiresponse.Error(w, http.StatusNotFound, "任务不存在")
		return
	}
	task, err := h.service.Save(r.Context(), r.PathValue("id"), input, a.ID)
	if err != nil {
		apiresponse.Error(w, http.StatusBadRequest, err.Error())
		return
	}
	apiresponse.OK(w, task)
}

func (h *PortalHTTPHandler) delete(w http.ResponseWriter, r *http.Request) {
	a, ok := h.account(w, r)
	if !ok {
		return
	}
	task, err := h.service.GetOwned(r.Context(), a.ID, r.PathValue("id"))
	if err != nil {
		apiresponse.Error(w, http.StatusNotFound, "任务不存在")
		return
	}
	if err := h.service.Delete(r.Context(), task.ID); err != nil {
		apiresponse.Error(w, http.StatusServiceUnavailable, "任务删除失败")
		return
	}
	apiresponse.OK(w, map[string]bool{"deleted": true})
}

func (h *PortalHTTPHandler) setEnabled(w http.ResponseWriter, r *http.Request, enabled bool) {
	a, ok := h.account(w, r)
	if !ok {
		return
	}
	task, err := h.service.GetOwned(r.Context(), a.ID, r.PathValue("id"))
	if err != nil {
		apiresponse.Error(w, http.StatusNotFound, "任务不存在")
		return
	}
	updated, err := h.service.SetEnabled(r.Context(), task.ID, enabled)
	if err != nil {
		apiresponse.Error(w, http.StatusServiceUnavailable, "任务状态更新失败")
		return
	}
	apiresponse.OK(w, updated)
}

func (h *PortalHTTPHandler) start(w http.ResponseWriter, r *http.Request)  { h.setEnabled(w, r, true) }
func (h *PortalHTTPHandler) pause(w http.ResponseWriter, r *http.Request)  { h.setEnabled(w, r, false) }

func (h *PortalHTTPHandler) runNow(w http.ResponseWriter, r *http.Request) {
	a, ok := h.account(w, r)
	if !ok {
		return
	}
	task, err := h.service.GetOwned(r.Context(), a.ID, r.PathValue("id"))
	if err != nil {
		apiresponse.Error(w, http.StatusNotFound, "任务不存在")
		return
	}
	if _, err := h.service.QueueManual(r.Context(), task.ID); err != nil {
		apiresponse.Error(w, http.StatusBadRequest, err.Error())
		return
	}
	apiresponse.OK(w, map[string]bool{"queued": true})
}

func (h *PortalHTTPHandler) runs(w http.ResponseWriter, r *http.Request) {
	a, ok := h.account(w, r)
	if !ok {
		return
	}
	task, err := h.service.GetOwned(r.Context(), a.ID, r.PathValue("id"))
	if err != nil {
		apiresponse.Error(w, http.StatusNotFound, "任务不存在")
		return
	}
	items, err := h.service.Runs(r.Context(), task.ID, 50)
	if err != nil {
		apiresponse.Error(w, http.StatusServiceUnavailable, "执行历史查询失败")
		return
	}
	apiresponse.OK(w, items)
}

func decodeJSON(w http.ResponseWriter, r *http.Request, target any) error {
	decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
	decoder.DisallowUnknownFields()
	if err := decoder.Decode(target); err != nil {
		apiresponse.Error(w, http.StatusBadRequest, "请求格式无效")
		return errors.New("bad request")
	}
	return nil
}
