package response

import (
	"context"
	"net/http"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	"haixun-backend/internal/types"

	"github.com/zeromicro/go-zero/rest/httpx"
)

func Write(ctx context.Context, w http.ResponseWriter, data any, err error) {
	if err != nil {
		status, body := buildError(err)
		httpx.WriteJsonCtx(ctx, w, status, body)
		return
	}

	httpx.WriteJsonCtx(ctx, w, http.StatusOK, types.Status{
		Code:    code.DefaultSuccessFullCodeInt,
		Message: code.DefaultSuccessMessage,
		Data:    data,
	})
}

func buildError(err error) (int, types.Status) {
	if appErr := app.FromError(err); appErr != nil {
		return appErr.HTTPStatus(), types.Status{
			Code:    int64(appErr.Code()),
			Message: appErr.Error(),
			Error: types.ErrorDetail{
				BizCode:  appErr.DisplayCode(),
				Scope:    int64(appErr.Scope()),
				Category: int64(appErr.Category()),
				Detail:   int64(appErr.Detail()),
			},
		}
	}

	fallback := app.For(code.Unset).SysInternal("internal server error")
	return http.StatusInternalServerError, types.Status{
		Code:    int64(fallback.Code()),
		Message: fallback.Error(),
		Error: types.ErrorDetail{
			BizCode:  fallback.DisplayCode(),
			Scope:    int64(fallback.Scope()),
			Category: int64(fallback.Category()),
			Detail:   int64(fallback.Detail()),
		},
	}
}
