package workbench

import (
	"errors"
	"io"
	"mime/multipart"
	"net/http"
	"net/url"
	"strconv"
	"strings"

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

// FilesAdminHTTPHandler exposes the system-scoped file store to the admin
// console. Objects are uploaded through the gateway (never exposing MinIO), so
// the S3 credentials stay inside the API container.
type FilesAdminHTTPHandler struct {
	files    *FileService
	identity *identity.Service
	mux      *http.ServeMux
}

func NewFilesAdminHTTPHandler(files *FileService, identityService *identity.Service) *FilesAdminHTTPHandler {
	h := &FilesAdminHTTPHandler{files: files, identity: identityService, mux: http.NewServeMux()}
	h.mux.HandleFunc("POST /api/v1/admin/files", h.upload)
	h.mux.HandleFunc("GET /api/v1/admin/files", h.list)
	h.mux.HandleFunc("GET /api/v1/admin/files/{id}/download", h.download)
	h.mux.HandleFunc("DELETE /api/v1/admin/files/{id}", h.delete)
	return h
}

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

func (h *FilesAdminHTTPHandler) require(w http.ResponseWriter, r *http.Request, permission string) (identity.Account, bool) {
	account, err := h.identity.Authenticate(r.Context(), identity.KindAdmin, r.Header.Get("Authorization"))
	if err != nil {
		apiresponse.Error(w, http.StatusUnauthorized, "登录状态无效")
		return identity.Account{}, false
	}
	if !identity.HasPermission(account, permission) {
		apiresponse.Error(w, http.StatusForbidden, "缺少文件管理权限")
		return identity.Account{}, false
	}
	return account, true
}

// firstFilePart pulls the multipart "file" part out of a streaming request so
// uploads never need to buffer the whole body in memory.
func firstFilePart(r *http.Request) (*multipart.Part, error) {
	reader, err := r.MultipartReader()
	if err != nil {
		return nil, err
	}
	for {
		part, err := reader.NextPart()
		if err == io.EOF {
			return nil, errors.New("no file part")
		}
		if err != nil {
			return nil, err
		}
		if part.FormName() == "file" {
			return part, nil
		}
	}
}

// upload accepts either multipart/form-data (browser) or a raw body with a
// ?filename= query parameter (scripting). The size ceiling is enforced by the
// service's LimitReader, not by buffering.
func (h *FilesAdminHTTPHandler) upload(w http.ResponseWriter, r *http.Request) {
	a, ok := h.require(w, r, identity.PermissionFileManage)
	if !ok {
		return
	}
	var (
		body        io.Reader
		originalName = strings.TrimSpace(r.URL.Query().Get("filename"))
		contentType  = r.Header.Get("Content-Type")
	)
	if strings.HasPrefix(contentType, "multipart/form-data") {
		part, err := firstFilePart(r)
		if err != nil {
			apiresponse.Error(w, http.StatusBadRequest, "缺少上传文件")
			return
		}
		defer part.Close()
		body = part
		originalName = part.FileName()
		if ct := part.Header.Get("Content-Type"); ct != "" {
			contentType = ct
		}
	}
	if originalName == "" {
		apiresponse.Error(w, http.StatusBadRequest, "缺少文件名")
		return
	}
	obj, err := h.files.Upload(r.Context(), "system", nil, a.ID, originalName, contentType, body)
	if err != nil {
		fileError(w, err)
		return
	}
	apiresponse.OK(w, obj)
}

func (h *FilesAdminHTTPHandler) list(w http.ResponseWriter, r *http.Request) {
	if _, ok := h.require(w, r, identity.PermissionFileRead); !ok {
		return
	}
	items, err := h.files.ListSystem(r.Context())
	if err != nil {
		fileError(w, err)
		return
	}
	apiresponse.OK(w, items)
}

func (h *FilesAdminHTTPHandler) download(w http.ResponseWriter, r *http.Request) {
	if _, ok := h.require(w, r, identity.PermissionFileRead); !ok {
		return
	}
	obj, err := h.files.GetSystem(r.Context(), r.PathValue("id"))
	if err != nil {
		fileError(w, err)
		return
	}
	serveFileContent(w, r, h.files, obj)
}

func (h *FilesAdminHTTPHandler) delete(w http.ResponseWriter, r *http.Request) {
	if _, ok := h.require(w, r, identity.PermissionFileManage); !ok {
		return
	}
	if err := h.files.DeleteSystem(r.Context(), r.PathValue("id")); err != nil {
		fileError(w, err)
		return
	}
	apiresponse.OK(w, map[string]bool{"deleted": true})
}

// serveFileContent streams the object body straight to the client with a
// Content-Disposition so the original filename is preserved on download.
func serveFileContent(w http.ResponseWriter, r *http.Request, files *FileService, obj FileObject) {
	reader, size, err := files.Open(r.Context(), obj)
	if err != nil {
		apiresponse.Error(w, http.StatusServiceUnavailable, "文件内容暂不可用")
		return
	}
	defer reader.Close()
	w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+url.PathEscape(obj.OriginalName))
	w.Header().Set("Content-Type", obj.ContentType)
	w.Header().Set("Content-Length", strconv.FormatInt(size, 10))
	_, _ = io.Copy(w, reader)
}

func fileError(w http.ResponseWriter, err error) {
	switch {
	case errors.Is(err, ErrNotFound):
		apiresponse.Error(w, http.StatusNotFound, "文件不存在")
	default:
		apiresponse.Error(w, http.StatusBadRequest, err.Error())
	}
}
