package handlers

import (
	"bufio"
	"bytes"
	"context"
	"errors"
	"io"
	"log/slog"
	"net/http"
	"reflect"
	"strings"
	"sync"
	"testing"
	"time"
	"unsafe"

	"github.com/gofiber/fiber/v2"
	"github.com/valyala/fasthttp"

	filemanager "wucher/internal/domain/file_manager"
	filemanagerrealtime "wucher/internal/realtime/filemanager"
	"wucher/internal/shared/pkg/uuidv7"
)

type fileManagerAttachmentHandlerServiceMock struct {
	filemanager.Service

	createAttachmentFn func(context.Context, filemanager.CreateAttachmentParams) (*filemanager.Attachment, error)
	getAttachmentFn    func(context.Context, []byte) (*filemanager.Attachment, error)
	getFileFn          func(context.Context, []byte) (*filemanager.File, error)
	listAttachmentsFn  func(context.Context, filemanager.ListAttachmentsParams) ([]filemanager.Attachment, int64, error)
	deleteAttachmentFn func(context.Context, []byte) error
}

func (m *fileManagerAttachmentHandlerServiceMock) CreateAttachment(ctx context.Context, params filemanager.CreateAttachmentParams) (*filemanager.Attachment, error) {
	if m.createAttachmentFn != nil {
		return m.createAttachmentFn(ctx, params)
	}
	return nil, nil
}

func (m *fileManagerAttachmentHandlerServiceMock) GetAttachmentByID(ctx context.Context, id []byte) (*filemanager.Attachment, error) {
	if m.getAttachmentFn != nil {
		return m.getAttachmentFn(ctx, id)
	}
	return nil, nil
}

func (m *fileManagerAttachmentHandlerServiceMock) GetFileByID(ctx context.Context, id []byte) (*filemanager.File, error) {
	if m.getFileFn != nil {
		return m.getFileFn(ctx, id)
	}
	return nil, nil
}

func (m *fileManagerAttachmentHandlerServiceMock) ListAttachmentsByReference(ctx context.Context, params filemanager.ListAttachmentsParams) ([]filemanager.Attachment, int64, error) {
	if m.listAttachmentsFn != nil {
		return m.listAttachmentsFn(ctx, params)
	}
	return nil, 0, nil
}

func (m *fileManagerAttachmentHandlerServiceMock) DeleteAttachment(ctx context.Context, id []byte) error {
	if m.deleteAttachmentFn != nil {
		return m.deleteAttachmentFn(ctx, id)
	}
	return nil
}

func newFileManagerAttachmentHandlerTestApp(h *FileManagerAttachmentHandler, actor []byte) *fiber.App {
	app := fiber.New()
	app.Use(func(c *fiber.Ctx) error {
		if len(actor) > 0 {
			c.Locals("user_id", append([]byte(nil), actor...))
		}
		return c.Next()
	})
	app.Post("/api/v1/file-manager/attachments/create", h.CreateAttachment)
	app.Get("/api/v1/file-manager/attachments/get/:uuid", h.GetAttachment)
	app.Get("/api/v1/file-manager/attachments/get-all", h.ListAttachments)
	app.Delete("/api/v1/file-manager/attachments/delete/:uuid", h.DeleteAttachment)
	return app
}

func newFileManagerEventsHandlerTestApp(h *FileManagerEventsHandler, actor []byte) *fiber.App {
	app := fiber.New()
	app.Use(func(c *fiber.Ctx) error {
		if actor != nil {
			c.Locals("user_id", append([]byte(nil), actor...))
		}
		return c.Next()
	})
	app.Get("/api/v1/file-manager/events", h.Stream)
	return app
}

func TestFileManagerActionAndErrorHelpers(t *testing.T) {
	id := uuidv7.MustBytes()
	resource := fileManagerActionResultResource("file_manager_delete_result", id, " trashed ", " "+mustUUIDStringFileManager(t, uuidv7.MustBytes())+" ")
	if resource.Type != "file_manager_delete_result" || resource.ID == "" || resource.Attributes.Status != "trashed" {
		t.Fatalf("unexpected action resource: %#v", resource)
	}
	if resource.Attributes.Location == nil || resource.Attributes.Location.FolderID == "" {
		t.Fatalf("expected action location")
	}
	noLocation := fileManagerActionResultResource("file_manager_restore_result", id, "ready", " ")
	if noLocation.Attributes.Location != nil {
		t.Fatalf("expected nil location")
	}

	tests := []struct {
		err        error
		wantStatus int
		wantTitle  string
	}{
		{err: errors.New("plain"), wantStatus: http.StatusBadRequest, wantTitle: "Action failed"},
		{err: filemanager.ErrStorageUnavailable, wantStatus: http.StatusServiceUnavailable, wantTitle: "Storage unavailable"},
		{err: filemanager.ErrFileProcessingQueueDisabled, wantStatus: http.StatusServiceUnavailable, wantTitle: "Queue unavailable"},
		{err: filemanager.ErrUploadIntentRepositoryDisabled, wantStatus: http.StatusServiceUnavailable, wantTitle: "Upload intent unavailable"},
		{err: filemanager.ErrFolderNotFound, wantStatus: http.StatusNotFound, wantTitle: "Not found"},
		{err: filemanager.ErrFileNotFound, wantStatus: http.StatusNotFound, wantTitle: "Not found"},
		{err: filemanager.ErrAttachmentNotFound, wantStatus: http.StatusNotFound, wantTitle: "Attachment not found"},
		{err: filemanager.ErrUploadIntentNotFound, wantStatus: http.StatusNotFound, wantTitle: "Upload intent not found"},
		{err: filemanager.ErrFileStatusConflict, wantStatus: http.StatusConflict, wantTitle: "Conflict"},
		{err: filemanager.ErrUploadIntentExpired, wantStatus: http.StatusConflict, wantTitle: "Upload intent conflict"},
		{err: filemanager.ErrDuplicateName, wantStatus: http.StatusUnprocessableEntity, wantTitle: "Validation error"},
		{err: filemanager.ErrAttachmentRepositoryDisabled, wantStatus: http.StatusServiceUnavailable, wantTitle: "Attachment service unavailable"},
	}
	for _, tc := range tests {
		status, title, detail, _, _ := mapFileManagerActionError("Action failed", tc.err)
		if status != tc.wantStatus || title != tc.wantTitle || detail == "" {
			t.Fatalf("unexpected map result for %v: %d %q %q", tc.err, status, title, detail)
		}
	}
}

func TestFileManagerAttachmentHandler(t *testing.T) {
	t.Run("create attachment", func(t *testing.T) {
		fileID := uuidv7.MustBytes()
		attachmentID := uuidv7.MustBytes()
		now := time.Now().UTC()
		category := "document"
		sortOrder := 2
		isPrimary := true
		svc := &fileManagerAttachmentHandlerServiceMock{
			createAttachmentFn: func(_ context.Context, params filemanager.CreateAttachmentParams) (*filemanager.Attachment, error) {
				return &filemanager.Attachment{
					ID:         attachmentID,
					FileID:     params.FileID,
					RefType:    params.RefType,
					RefID:      params.RefID,
					Category:   params.Category,
					SortOrder:  params.SortOrder,
					IsPrimary:  params.IsPrimary,
					AttachedBy: params.ActorID,
					CreatedAt:  now,
					UpdatedAt:  now,
				}, nil
			},
		}
		app := newFileManagerAttachmentHandlerTestApp(NewFileManagerAttachmentHandler(svc), uuidv7.MustBytes())
		body := []byte(`{"data":{"type":"file_manager_attachment_create","attributes":{"file_id":"` + mustUUIDStringFileManager(t, fileID) + `","ref_type":"helicopter","ref_id":"abc","category":"` + category + `","sort_order":` + "2" + `,"is_primary":true}}}`)
		resp, raw := doJSONRequestFileManagerFile(t, app, http.MethodPost, "/api/v1/file-manager/attachments/create", body)
		if resp.StatusCode != http.StatusCreated {
			t.Fatalf("expected 201, got %d", resp.StatusCode)
		}
		out := decodeJSONMapFileManagerFile(t, raw)
		data := mapField(t, out["data"], "data")
		if data["type"] != "file_manager_attachment" {
			t.Fatalf("unexpected type: %#v", data["type"])
		}
		attrs := mapField(t, data["attributes"], "attributes")
		if attrs["sort_order"] != float64(sortOrder) || attrs["is_primary"] != isPrimary {
			t.Fatalf("unexpected attachment attrs: %#v", attrs)
		}
	})

	t.Run("attachment validations and errors", func(t *testing.T) {
		attachmentID := uuidv7.MustBytes()
		fileID := uuidv7.MustBytes()
		now := time.Now().UTC()
		category := "image"
		svc := &fileManagerAttachmentHandlerServiceMock{
			createAttachmentFn: func(context.Context, filemanager.CreateAttachmentParams) (*filemanager.Attachment, error) {
				return nil, filemanager.ErrAttachmentAlreadyExists
			},
			getAttachmentFn: func(_ context.Context, id []byte) (*filemanager.Attachment, error) {
				if bytes.Equal(id, attachmentID) {
					return &filemanager.Attachment{
						ID:         id,
						FileID:     fileID,
						RefType:    "helicopter",
						RefID:      "ref-1",
						Category:   &category,
						SortOrder:  1,
						IsPrimary:  true,
						AttachedBy: uuidv7.MustBytes(),
						CreatedAt:  now,
						UpdatedAt:  now,
					}, nil
				}
				return nil, filemanager.ErrAttachmentNotFound
			},
			listAttachmentsFn: func(_ context.Context, params filemanager.ListAttachmentsParams) ([]filemanager.Attachment, int64, error) {
				if params.RefType == "boom" {
					return nil, 0, filemanager.ErrAttachmentRepositoryDisabled
				}
				return []filemanager.Attachment{{
					ID:         attachmentID,
					FileID:     fileID,
					RefType:    params.RefType,
					RefID:      params.RefID,
					Category:   params.Category,
					SortOrder:  1,
					IsPrimary:  true,
					AttachedBy: uuidv7.MustBytes(),
					CreatedAt:  now,
					UpdatedAt:  now,
				}}, 1, nil
			},
			deleteAttachmentFn: func(_ context.Context, id []byte) error {
				if bytes.Equal(id, attachmentID) {
					return nil
				}
				return filemanager.ErrAttachmentNotFound
			},
		}
		app := newFileManagerAttachmentHandlerTestApp(NewFileManagerAttachmentHandler(svc), uuidv7.MustBytes())

		resp, _ := doJSONRequestFileManagerFile(t, app, http.MethodPost, "/api/v1/file-manager/attachments/create", []byte(`{`))
		if resp.StatusCode != http.StatusBadRequest {
			t.Fatalf("expected 400 invalid json, got %d", resp.StatusCode)
		}
		resp, _ = doJSONRequestFileManagerFile(t, app, http.MethodPost, "/api/v1/file-manager/attachments/create", []byte(`{"data":{"type":"file_manager_attachment_create","attributes":{"file_id":"bad","ref_type":"helicopter","ref_id":"abc"}}}`))
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422 invalid file id, got %d", resp.StatusCode)
		}
		resp, _ = doJSONRequestFileManagerFile(t, app, http.MethodPost, "/api/v1/file-manager/attachments/create", []byte(`{"data":{"type":"file_manager_attachment_create","attributes":{"file_id":"`+mustUUIDStringFileManager(t, fileID)+`","ref_type":"helicopter","ref_id":"abc","sort_order":-1}}}`))
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422 invalid sort_order, got %d", resp.StatusCode)
		}
		resp, _ = doJSONRequestFileManagerFile(t, app, http.MethodPost, "/api/v1/file-manager/attachments/create", []byte(`{"data":{"type":"file_manager_attachment_create","attributes":{"file_id":"`+mustUUIDStringFileManager(t, fileID)+`","ref_type":"helicopter","ref_id":"abc"}}}`))
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422 create action error, got %d", resp.StatusCode)
		}

		resp, _ = doJSONRequestFileManagerFile(t, app, http.MethodGet, "/api/v1/file-manager/attachments/get/zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz", nil)
		if resp.StatusCode != http.StatusNotFound {
			t.Fatalf("expected 404 invalid uuid path handling, got %d", resp.StatusCode)
		}
		resp, raw := doJSONRequestFileManagerFile(t, app, http.MethodGet, "/api/v1/file-manager/attachments/get/"+mustUUIDStringFileManager(t, attachmentID), nil)
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200 get attachment, got %d", resp.StatusCode)
		}
		if mapField(t, decodeJSONMapFileManagerFile(t, raw)["data"], "data")["type"] != "file_manager_attachment" {
			t.Fatalf("expected attachment resource")
		}
		nilRowID := mustUUIDStringFileManager(t, uuidv7.MustBytes())
		svc.getAttachmentFn = func(_ context.Context, id []byte) (*filemanager.Attachment, error) {
			if bytes.Equal(id, attachmentID) {
				return &filemanager.Attachment{
					ID:         id,
					FileID:     fileID,
					RefType:    "helicopter",
					RefID:      "ref-1",
					Category:   &category,
					SortOrder:  1,
					IsPrimary:  true,
					AttachedBy: uuidv7.MustBytes(),
					CreatedAt:  now,
					UpdatedAt:  now,
				}, nil
			}
			if idString(id) == nilRowID {
				return nil, nil
			}
			return nil, filemanager.ErrAttachmentNotFound
		}
		resp, _ = doJSONRequestFileManagerFile(t, app, http.MethodGet, "/api/v1/file-manager/attachments/get/"+nilRowID, nil)
		if resp.StatusCode != http.StatusNotFound {
			t.Fatalf("expected 404 nil row, got %d", resp.StatusCode)
		}
		resp, _ = doJSONRequestFileManagerFile(t, app, http.MethodGet, "/api/v1/file-manager/attachments/get/"+mustUUIDStringFileManager(t, uuidv7.MustBytes()), nil)
		if resp.StatusCode != http.StatusNotFound {
			t.Fatalf("expected 404 get attachment not found, got %d", resp.StatusCode)
		}

		resp, _ = doJSONRequestFileManagerFile(t, app, http.MethodGet, "/api/v1/file-manager/attachments/get-all", nil)
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422 list attachments missing ref, got %d", resp.StatusCode)
		}
		resp, raw = doJSONRequestFileManagerFile(t, app, http.MethodGet, "/api/v1/file-manager/attachments/get-all?ref_type=helicopter&ref_id=ref-1&page[number]=0&page[size]=999", nil)
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200 list attachments, got %d", resp.StatusCode)
		}
		meta := mapField(t, decodeJSONMapFileManagerFile(t, raw)["meta"], "meta")
		if meta["total"] == nil {
			t.Fatalf("expected total in meta, got %#v", meta)
		}
		resp, _ = doJSONRequestFileManagerFile(t, app, http.MethodGet, "/api/v1/file-manager/attachments/get-all?ref_type=boom&ref_id=ref-1", nil)
		if resp.StatusCode != http.StatusServiceUnavailable {
			t.Fatalf("expected 503 list attachments action error, got %d", resp.StatusCode)
		}

		resp, _ = doJSONRequestFileManagerFile(t, app, http.MethodDelete, "/api/v1/file-manager/attachments/delete/"+mustUUIDStringFileManager(t, attachmentID), nil)
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200 delete attachment, got %d", resp.StatusCode)
		}
		resp, _ = doJSONRequestFileManagerFile(t, app, http.MethodDelete, "/api/v1/file-manager/attachments/delete/"+mustUUIDStringFileManager(t, uuidv7.MustBytes()), nil)
		if resp.StatusCode != http.StatusNotFound {
			t.Fatalf("expected 404 delete attachment not found, got %d", resp.StatusCode)
		}
		resp, _ = doJSONRequestFileManagerFile(t, app, http.MethodDelete, "/api/v1/file-manager/attachments/delete/zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz", nil)
		if resp.StatusCode != http.StatusNotFound {
			t.Fatalf("expected 404 invalid delete uuid path handling, got %d", resp.StatusCode)
		}
	})

	t.Run("attachment helpers", func(t *testing.T) {
		app := fiber.New()
		h := NewFileManagerAttachmentHandler(&fileManagerAttachmentHandlerServiceMock{})
		app.Get("/:uuid", func(c *fiber.Ctx) error {
			if _, err := h.parseUUIDParam(c, "uuid", "/path/uuid"); err != nil {
				return err
			}
			page, size, offset := parseFileManagerAttachmentPagination(c)
			if page != 1 || size != 100 || offset != 0 {
				t.Fatalf("unexpected pagination %d %d %d", page, size, offset)
			}
			return nil
		})
		req, _ := http.NewRequest(http.MethodGet, "/"+mustUUIDStringFileManager(t, uuidv7.MustBytes())+"?page[number]=0&page[size]=999", nil)
		resp, err := app.Test(req)
		if err != nil || resp.StatusCode != http.StatusOK {
			t.Fatalf("unexpected app.Test result: %v %v", resp, err)
		}

		category := " doc "
		row := &filemanager.Attachment{
			ID:         uuidv7.MustBytes(),
			FileID:     uuidv7.MustBytes(),
			RefType:    " helicopter ",
			RefID:      " ref-1 ",
			Category:   &category,
			SortOrder:  3,
			IsPrimary:  true,
			AttachedBy: uuidv7.MustBytes(),
			CreatedAt:  time.Now().UTC(),
			UpdatedAt:  time.Now().UTC(),
		}
		if fileManagerAttachmentResource(nil).Type != "file_manager_attachment" {
			t.Fatalf("expected nil attachment fallback type")
		}
		resource := fileManagerAttachmentResource(row)
		if resource.Attributes.Category != "doc" || resource.Attributes.RefType != "helicopter" || resource.Attributes.RefID != "ref-1" {
			t.Fatalf("unexpected attachment resource attrs: %#v", resource.Attributes)
		}
	})
}

func TestFileManagerEventsHandlerAndHelpers(t *testing.T) {
	t.Run("stream guard rails", func(t *testing.T) {
		appNil := newFileManagerEventsHandlerTestApp(NewFileManagerEventsHandler(nil), nil)
		req, _ := http.NewRequest(http.MethodGet, "/api/v1/file-manager/events", nil)
		resp, err := appNil.Test(req)
		if err != nil {
			t.Fatalf("unexpected nil-hub app.Test error: %v", err)
		}
		if resp.StatusCode != http.StatusServiceUnavailable {
			t.Fatalf("expected 503 nil hub, got %d", resp.StatusCode)
		}

		appShortActor := newFileManagerEventsHandlerTestApp(NewFileManagerEventsHandler(filemanagerrealtime.NewHub(1, slog.Default())), []byte("short"))
		req, _ = http.NewRequest(http.MethodGet, "/api/v1/file-manager/events", nil)
		resp, err = appShortActor.Test(req)
		if err != nil {
			t.Fatalf("unexpected short-actor app.Test error: %v", err)
		}
		if resp.StatusCode != http.StatusUnauthorized {
			t.Fatalf("expected 401 invalid actor, got %d", resp.StatusCode)
		}

		appBadFilter := fiber.New()
		fctx := &fasthttp.RequestCtx{}
		fctx.Request.SetRequestURI("/api/v1/file-manager/events?folder_id=zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz")
		c := appBadFilter.AcquireCtx(fctx)
		c.Locals("user_id", uuidv7.MustBytes())
		err = NewFileManagerEventsHandler(filemanagerrealtime.NewHub(1, slog.Default())).Stream(c)
		appBadFilter.ReleaseCtx(c)
		if err != nil {
			t.Fatalf("unexpected direct stream filter error return: %v", err)
		}
		if fctx.Response.StatusCode() != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422 invalid folder filter, got %d", fctx.Response.StatusCode())
		}

		app := newFileManagerEventsHandlerTestApp(NewFileManagerEventsHandler(filemanagerrealtime.NewHub(1, slog.Default())), uuidv7.MustBytes())
		req, _ = http.NewRequest(http.MethodGet, "/api/v1/file-manager/events", nil)
		_, err = app.Test(req, 50)
		if err == nil {
			t.Fatalf("expected streaming request timeout to stop test request")
		}

		hub := filemanagerrealtime.NewHub(1, slog.Default())
		actor := uuidv7.MustBytes()
		userUUID, _ := uuidv7.BytesToString(actor)
		appDirect := fiber.New()
		fctx2 := &fasthttp.RequestCtx{}
		fctx2.Request.SetRequestURI("/api/v1/file-manager/events")
		c2 := appDirect.AcquireCtx(fctx2)
		c2.Locals("user_id", actor)
		if err := NewFileManagerEventsHandler(hub).Stream(c2); err != nil {
			t.Fatalf("unexpected direct stream setup error: %v", err)
		}
		folderID := mustUUIDStringFileManager(t, uuidv7.MustBytes())
		hub.PublishToUsers([]string{userUUID}, filemanagerrealtime.FileStatusEvent{
			FileUUID:   mustUUIDStringFileManager(t, uuidv7.MustBytes()),
			FolderUUID: &folderID,
			Status:     "ready",
			Name:       "image.png",
			MimeType:   "image/png",
			UpdatedAt:  time.Now().UTC().Format(time.RFC3339),
		})
		go func() {
			time.Sleep(10 * time.Millisecond)
			closeFirstHubSubscriberForUser(hub, userUUID)
		}()
		respStr := c2.Context().Response.String()
		appDirect.ReleaseCtx(c2)
		if !strings.Contains(respStr, ": connected") || !strings.Contains(respStr, "event: "+fileManagerSSEEventName) {
			t.Fatalf("unexpected stream response output: %q", respStr)
		}

		filteredHub := filemanagerrealtime.NewHub(2, slog.Default())
		filterActor := uuidv7.MustBytes()
		filterUserUUID, _ := uuidv7.BytesToString(filterActor)
		filterFileID := mustUUIDStringFileManager(t, uuidv7.MustBytes())
		appFiltered := fiber.New()
		filterCtx := &fasthttp.RequestCtx{}
		filterCtx.Request.SetRequestURI("/api/v1/file-manager/events?file_id=" + filterFileID)
		c3 := appFiltered.AcquireCtx(filterCtx)
		c3.Locals("user_id", filterActor)
		if err := NewFileManagerEventsHandler(filteredHub).Stream(c3); err != nil {
			t.Fatalf("unexpected filtered stream setup error: %v", err)
		}
		filteredHub.PublishToUsers([]string{filterUserUUID}, filemanagerrealtime.FileStatusEvent{
			FileUUID:  mustUUIDStringFileManager(t, uuidv7.MustBytes()),
			Status:    "processing",
			Name:      "skip.png",
			UpdatedAt: time.Now().UTC().Format(time.RFC3339),
		})
		filteredHub.PublishToUsers([]string{filterUserUUID}, filemanagerrealtime.FileStatusEvent{
			FileUUID:  filterFileID,
			Status:    "ready",
			Name:      "keep.png",
			UpdatedAt: time.Now().UTC().Format(time.RFC3339),
		})
		go func() {
			time.Sleep(10 * time.Millisecond)
			closeFirstHubSubscriberForUser(filteredHub, filterUserUUID)
		}()
		filteredRespStr := c3.Context().Response.String()
		appFiltered.ReleaseCtx(c3)
		if strings.Contains(filteredRespStr, "skip.png") || !strings.Contains(filteredRespStr, "keep.png") {
			t.Fatalf("unexpected filtered stream response output: %q", filteredRespStr)
		}

		doneHub := filemanagerrealtime.NewHub(1, slog.Default())
		doneActor := uuidv7.MustBytes()
		doneUserUUID, _ := uuidv7.BytesToString(doneActor)
		appDone := fiber.New()
		doneCtx := &fasthttp.RequestCtx{}
		doneCtx.Request.SetRequestURI("/api/v1/file-manager/events")
		c4 := appDone.AcquireCtx(doneCtx)
		c4.Locals("user_id", doneActor)
		if err := NewFileManagerEventsHandler(doneHub).Stream(c4); err != nil {
			t.Fatalf("unexpected done stream setup error: %v", err)
		}
		go func() {
			time.Sleep(10 * time.Millisecond)
			signalDoneFirstHubSubscriberForUser(doneHub, doneUserUUID)
		}()
		doneRespStr := c4.Context().Response.String()
		appDone.ReleaseCtx(c4)
		if !strings.Contains(doneRespStr, ": connected") {
			t.Fatalf("unexpected done stream response output: %q", doneRespStr)
		}
	})

	t.Run("parse filter match payload and sse writers", func(t *testing.T) {
		fileID1 := mustUUIDStringFileManager(t, uuidv7.MustBytes())
		fileID2 := mustUUIDStringFileManager(t, uuidv7.MustBytes())
		folderID := mustUUIDStringFileManager(t, uuidv7.MustBytes())
		app := fiber.New()
		fctx := &fasthttp.RequestCtx{}
		fctx.Request.URI().SetQueryString("folder_id=" + folderID + "&file_id=" + fileID1 + "&file_ids=" + fileID1 + "," + fileID2)
		c := app.AcquireCtx(fctx)
		filter, err := parseFileManagerSSEFilter(c)
		app.ReleaseCtx(c)
		if err != nil {
			t.Fatalf("unexpected parse filter error: %v", err)
		}
		matched := filter.folderID != nil && len(filter.fileIDs) == 2 && filter.match(filemanagerrealtime.FileStatusEvent{FileUUID: strings.ToUpper(fileID1), FolderUUID: filter.folderID})
		unmatchedEmpty := filter.match(filemanagerrealtime.FileStatusEvent{FileUUID: ""})
		unmatchedFolderless := filter.match(filemanagerrealtime.FileStatusEvent{FileUUID: fileID1})
		if !matched || unmatchedEmpty || unmatchedFolderless {
			t.Fatalf("unexpected match results matched=%v empty=%v folderless=%v", matched, unmatchedEmpty, unmatchedFolderless)
		}

		payload := mapFileStatusEventToSSEPayload(filemanagerrealtime.FileStatusEvent{
			FileUUID:   " file-id ",
			FolderUUID: filter.folderID,
			Status:     " ready ",
			Name:       " name ",
			MimeType:   " image/png ",
			UpdatedAt:  " now ",
		})
		payloadFolder := ""
		if payload.FolderID != nil {
			payloadFolder = *payload.FolderID
		}
		payloadFileID := payload.FileID
		payloadStatus := payload.Status
		if payloadFileID != "file-id" || payloadStatus != "ready" || payloadFolder != folderID {
			t.Fatalf("unexpected payload values: file=%q status=%q folder=%q", payloadFileID, payloadStatus, payloadFolder)
		}

		emptyCtx := &fasthttp.RequestCtx{}
		emptyCtx.Request.SetRequestURI("/")
		c = app.AcquireCtx(emptyCtx)
		emptyFilter, err := parseFileManagerSSEFilter(c)
		app.ReleaseCtx(c)
		if err != nil || emptyFilter.folderID != nil || len(emptyFilter.fileIDs) != 0 {
			t.Fatalf("unexpected empty filter result: %#v err=%v", emptyFilter, err)
		}

		var buf bytes.Buffer
		writer := bufio.NewWriter(&buf)
		if !writeSSEComment(writer, " connected ") {
			t.Fatalf("expected comment write success")
		}
		if !strings.Contains(buf.String(), ": connected") {
			t.Fatalf("unexpected comment output %q", buf.String())
		}
		buf.Reset()
		writer = bufio.NewWriter(&buf)
		if !writeSSEDataEvent(writer, " file.updated ", map[string]any{"status": "ready"}) {
			t.Fatalf("expected data event write success")
		}
		if !strings.Contains(buf.String(), "event: file.updated") || !strings.Contains(buf.String(), "\"status\":\"ready\"") {
			t.Fatalf("unexpected data event output %q", buf.String())
		}
	})

	t.Run("sse writer failures", func(t *testing.T) {
		bw := bufio.NewWriter(errWriter{})
		if writeSSEComment(bw, "x") {
			t.Fatalf("expected comment writer failure")
		}
		bw = bufio.NewWriterSize(&failOnWriteWriter{failOn: 1}, 1)
		if writeSSEComment(bw, strings.Repeat("x", 32)) {
			t.Fatalf("expected comment immediate write failure")
		}
		bw = bufio.NewWriter(errWriter{})
		if writeSSEDataEvent(bw, "event", map[string]any{"status": "ready"}) {
			t.Fatalf("expected data writer failure")
		}
		bw = bufio.NewWriterSize(&failOnWriteWriter{failOn: 1}, 1)
		if writeSSEDataEvent(bw, strings.Repeat("e", 32), map[string]any{"status": "ready"}) {
			t.Fatalf("expected data event first write failure")
		}
		bw = bufio.NewWriterSize(&failOnWriteWriter{failOn: 2}, 1)
		if writeSSEDataEvent(bw, "event", map[string]any{"status": "ready"}) {
			t.Fatalf("expected data event second write failure")
		}
		bw = bufio.NewWriter(io.Discard)
		if writeSSEDataEvent(bw, "event", func() {}) {
			t.Fatalf("expected marshal failure")
		}
	})
}

type errWriter struct{}

func (errWriter) Write([]byte) (int, error) {
	return 0, errors.New("write fail")
}

type failOnWriteWriter struct {
	failOn int
	calls  int
}

func (w *failOnWriteWriter) Write(p []byte) (int, error) {
	w.calls++
	if w.calls >= w.failOn {
		return 0, errors.New("write fail")
	}
	return len(p), nil
}

func closeFirstHubSubscriberForUser(hub *filemanagerrealtime.Hub, userUUID string) {
	if hub == nil {
		return
	}
	hubValue := reflect.ValueOf(hub).Elem()
	subscribersField := reflect.NewAt(hubValue.FieldByName("subscribers").Type(), unsafe.Pointer(hubValue.FieldByName("subscribers").UnsafeAddr())).Elem()
	byUser := subscribersField.MapIndex(reflect.ValueOf(strings.ToLower(strings.TrimSpace(userUUID))))
	if !byUser.IsValid() || byUser.Len() == 0 {
		return
	}
	iter := byUser.MapRange()
	if !iter.Next() {
		return
	}
	sub := iter.Value()
	if sub.IsNil() {
		return
	}
	subElem := sub.Elem()
	eventsField := reflect.NewAt(subElem.FieldByName("events").Type(), unsafe.Pointer(subElem.FieldByName("events").UnsafeAddr())).Elem()
	eventsField.Close()
}

func signalDoneFirstHubSubscriberForUser(hub *filemanagerrealtime.Hub, userUUID string) {
	if hub == nil {
		return
	}
	hubValue := reflect.ValueOf(hub).Elem()
	subscribersField := reflect.NewAt(hubValue.FieldByName("subscribers").Type(), unsafe.Pointer(hubValue.FieldByName("subscribers").UnsafeAddr())).Elem()
	byUser := subscribersField.MapIndex(reflect.ValueOf(strings.ToLower(strings.TrimSpace(userUUID))))
	if !byUser.IsValid() || byUser.Len() == 0 {
		return
	}
	iter := byUser.MapRange()
	if !iter.Next() {
		return
	}
	sub := iter.Value()
	if sub.IsNil() {
		return
	}
	subElem := sub.Elem()
	closeOnceField := reflect.NewAt(subElem.FieldByName("closeOnce").Type(), unsafe.Pointer(subElem.FieldByName("closeOnce").UnsafeAddr())).Elem()
	closeOncePtr := (*sync.Once)(unsafe.Pointer(closeOnceField.UnsafeAddr()))
	closeOncePtr.Do(func() {})
	doneField := reflect.NewAt(subElem.FieldByName("done").Type(), unsafe.Pointer(subElem.FieldByName("done").UnsafeAddr())).Elem()
	doneField.Close()
}
