import {
  DeleteObjectCommand,
  GetObjectCommand,
  HeadObjectCommand,
  ListObjectsV2Command,
  PutObjectCommand,
  S3Client,
} from "@aws-sdk/client-s3";
import { sdkStreamMixin } from "@smithy/util-stream";
import type { TabloFoldersMetadata } from "@xtablo/shared-types";
import { mockClient } from "aws-sdk-client-mock";
import { testClient } from "hono/testing";
import { Readable } from "stream";
import { beforeAll, beforeEach, describe, expect, it } from "vitest";
import { createConfig } from "../../config.js";
import { MiddlewareManager } from "../../middlewares/middleware.js";
import { getMainRouter } from "../../routers/index.js";
import { clearTabloDataCachesForTests } from "../../routers/tablo_data.js";
import type { TestUserData } from "../helpers/dbSetup.js";
import { getTestUser } from "../helpers/dbSetup.js";

// Helper to create S3 stream from content
const createS3Stream = (content: string) => {
  const stream = new Readable();
  stream.push(content);
  stream.push(null);
  return sdkStreamMixin(stream);
};

// Create S3 mock
const s3Mock = mockClient(S3Client);

describe("TabloData Endpoint", () => {
  // In test mode, createConfig() reads from .env.test
  const config = createConfig();
  MiddlewareManager.initialize(config);
  const app = getMainRouter(config);
  // biome-ignore lint/suspicious/noExplicitAny: testClient requires any for dynamic route access
  const client = testClient(app) as any;

  const ownerUser = getTestUser("owner");
  const temporaryUser = getTestUser("temp");

  // biome-ignore lint/suspicious/noExplicitAny: testClient requires any for dynamic route access
  const getTabloFileNamesResponse = async (user: TestUserData, client: any, tabloId: string) => {
    const res = await client["tablo-data"][":tabloId"]["filenames"].$get(
      {
        param: { tabloId: tabloId },
      },
      {
        headers: { Authorization: `Bearer ${user.accessToken}` },
      }
    );
    return res;
  };

  // Store folder metadata state for tests
  let mockFolderMetadata: TabloFoldersMetadata = { folders: [], version: 1 };

  beforeAll(() => {
    // Reset mocks before all tests
    s3Mock.reset();

    // Mock ListObjectsV2Command (used by getTabloFileNames)
    s3Mock.on(ListObjectsV2Command).resolves({
      Contents: [
        { Key: "test_tablo_owner_private/file1.pdf" },
        { Key: "test_tablo_owner_private/file2.txt" },
        { Key: "test_tablo_owner_shared/shared-doc.pdf" },
      ],
    });

    // Mock GetObjectCommand (used by getTabloFile and getFolderMetadata)
    s3Mock.on(GetObjectCommand).callsFake((input) => {
      // Handle folder metadata requests
      if (input.Key?.endsWith(".tablo-folders.json")) {
        if (mockFolderMetadata.folders.length === 0 && mockFolderMetadata.version === 1) {
          // Return empty metadata (simulates file not found)
          return Promise.resolve({
            Body: createS3Stream(JSON.stringify(mockFolderMetadata)),
            ContentType: "application/json",
          });
        }
        return Promise.resolve({
          Body: createS3Stream(JSON.stringify(mockFolderMetadata)),
          ContentType: "application/json",
        });
      }
      // Handle regular file requests
      return Promise.resolve({
        Body: createS3Stream("test file content"),
        ContentType: "text/plain",
        LastModified: new Date("2025-11-12"),
      });
    });

    // Mock PutObjectCommand (used by postTabloFile and saveFolderMetadata)
    s3Mock.on(PutObjectCommand).callsFake((input) => {
      // Handle folder metadata saves
      if (input.Key?.endsWith(".tablo-folders.json") && input.Body) {
        mockFolderMetadata = JSON.parse(input.Body as string);
      }
      return Promise.resolve({});
    });

    // Mock DeleteObjectCommand (used by deleteTabloFile)
    s3Mock.on(DeleteObjectCommand).resolves({});

    // Mock HeadObjectCommand (used by deleteTabloFile ownership checks)
    s3Mock.on(HeadObjectCommand).callsFake((input) => {
      const key = input.Key ?? "";
      if (key.includes("temp-uploaded")) {
        return Promise.resolve({ Metadata: { "uploaded-by": temporaryUser.userId } });
      }
      return Promise.resolve({ Metadata: { "uploaded-by": ownerUser.userId } });
    });
  });

  beforeEach(() => {
    // Reset folder metadata before each test
    mockFolderMetadata = { folders: [], version: 1 };
    clearTabloDataCachesForTests();
  });

  describe("GET /tablo-data/:tabloId/filenames - Owner Access", () => {
    it("should allow owner to access their private tablo", async () => {
      const res = await getTabloFileNamesResponse(ownerUser, client, "test_tablo_owner_private");

      expect(res.status).toBe(200);
    });

    it("should allow owner to access their second private tablo", async () => {
      const res = await getTabloFileNamesResponse(ownerUser, client, "test_tablo_owner_private_2");

      expect(res.status).toBe(200);
    });

    it("should allow owner to access their shared tablo", async () => {
      const res = await getTabloFileNamesResponse(ownerUser, client, "test_tablo_owner_shared");

      expect(res.status).toBe(200);
    });

    it("should allow owner to access their team tablo", async () => {
      const res = await getTabloFileNamesResponse(ownerUser, client, "test_tablo_owner_team");

      expect(res.status).toBe(200);
    });

    it("should allow owner to access their completed tablo", async () => {
      const res = await getTabloFileNamesResponse(ownerUser, client, "test_tablo_owner_done");

      expect(res.status).toBe(200);
    });

    it("should allow owner with admin access to temp's shared tablo", async () => {
      const res = await getTabloFileNamesResponse(
        ownerUser,
        client,
        "test_tablo_temp_shared_admin"
      );

      expect(res.status).toBe(200);
    });

    it("should deny owner access to temp's private tablo", async () => {
      const res = await getTabloFileNamesResponse(ownerUser, client, "test_tablo_temp_private");

      expect(res.status).toBe(403);
    });

    it("should deny owner access to temp's second private tablo", async () => {
      const res = await getTabloFileNamesResponse(ownerUser, client, "test_tablo_temp_private_2");

      expect(res.status).toBe(403);
    });
  });

  describe("GET /tablo-data/:tabloId/filenames - Temp User Access", () => {
    it("should allow temp user to access owner's shared tablo", async () => {
      const res = await getTabloFileNamesResponse(temporaryUser, client, "test_tablo_owner_shared");

      expect(res.status).toBe(200);
    });

    it("should allow temp user to access owner's team tablo", async () => {
      const res = await getTabloFileNamesResponse(temporaryUser, client, "test_tablo_owner_team");

      expect(res.status).toBe(200);
    });

    it("should allow temp user to access their own private tablo", async () => {
      const res = await getTabloFileNamesResponse(temporaryUser, client, "test_tablo_temp_private");

      expect(res.status).toBe(200);
    });

    it("should allow temp user to access their second private tablo", async () => {
      const res = await getTabloFileNamesResponse(
        temporaryUser,
        client,
        "test_tablo_temp_private_2"
      );

      expect(res.status).toBe(200);
    });

    it("should allow temp user to access their shared tablo", async () => {
      const res = await getTabloFileNamesResponse(
        temporaryUser,
        client,
        "test_tablo_temp_shared_admin"
      );

      expect(res.status).toBe(200);
    });

    it("should deny temp user access to owner's private tablo", async () => {
      const res = await getTabloFileNamesResponse(
        temporaryUser,
        client,
        "test_tablo_owner_private"
      );

      expect(res.status).toBe(403);
    });

    it("should deny temp user access to owner's second private tablo", async () => {
      const res = await getTabloFileNamesResponse(
        temporaryUser,
        client,
        "test_tablo_owner_private_2"
      );

      expect(res.status).toBe(403);
    });

    it("should deny temp user access to owner's completed tablo", async () => {
      const res = await getTabloFileNamesResponse(temporaryUser, client, "test_tablo_owner_done");

      expect(res.status).toBe(403);
    });
  });

  describe("GET /tablo-data/:tabloId/filenames - Unauthenticated Access", () => {
    it("should deny unauthenticated access to any tablo", async () => {
      const res = await client["tablo-data"][":tabloId"]["filenames"].$get({
        param: { tabloId: "test_tablo_owner_private" },
      });

      expect(res.status).toBe(401);
    });

    it("should deny unauthenticated access to shared tablo", async () => {
      const res = await client["tablo-data"][":tabloId"]["filenames"].$get({
        param: { tabloId: "test_tablo_owner_shared" },
      });

      expect(res.status).toBe(401);
    });
  });

  describe("Non-existent Tablo", () => {
    it("should return 403 for non-existent tablo (owner)", async () => {
      const res = await getTabloFileNamesResponse(ownerUser, client, "non_existent_tablo");

      // Non-existent tablos return 403 (forbidden) because the user doesn't have access
      expect(res.status).toBe(403);
    });

    it("should return 403 for non-existent tablo (temp)", async () => {
      const res = await getTabloFileNamesResponse(temporaryUser, client, "non_existent_tablo");

      // Non-existent tablos return 403 (forbidden) because the user doesn't have access
      expect(res.status).toBe(403);
    });
  });

  describe("POST /tablo-data/:tabloId/:fileName - Upload File (Member Access)", () => {
    // Helper function to upload file
    const postTabloFileRequest = async (
      user: TestUserData,
      // biome-ignore lint/suspicious/noExplicitAny: testClient requires any for dynamic route access
      client: any,
      tabloId: string,
      fileName: string,
      content: string
    ) => {
      return await client["tablo-data"][":tabloId"][":fileName"].$post(
        {
          param: { tabloId, fileName },
          json: { content, contentType: "text/plain" },
        },
        {
          headers: { Authorization: `Bearer ${user.accessToken}` },
        }
      );
    };

    describe("Temporary User Access", () => {
      it("should allow temp user to upload file to their own tablo", async () => {
        const res = await postTabloFileRequest(
          temporaryUser,
          client,
          "test_tablo_temp_private",
          "new-file.txt",
          "Test content"
        );

        expect(res.status).toBe(200);
        const data = await res.json();
        expect(data.message).toBe("File uploaded successfully");
        expect(data.fileName).toBe("new-file.txt");
      });

      it("should allow temp user to upload file to owner's shared tablo", async () => {
        const res = await postTabloFileRequest(
          temporaryUser,
          client,
          "test_tablo_owner_shared",
          "temp-upload.txt",
          "Temporary user content"
        );

        expect(res.status).toBe(200);
        const data = await res.json();
        expect(data.message).toBe("File uploaded successfully");
      });

      it("should deny temp user from uploading file to owner's private tablo", async () => {
        const res = await postTabloFileRequest(
          temporaryUser,
          client,
          "test_tablo_owner_private",
          "unauthorized.txt",
          "Should fail"
        );

        expect(res.status).toBe(403);
      });
    });

    describe("Owner Access", () => {
      it("should allow owner to upload file to their own tablo", async () => {
        const res = await postTabloFileRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          "owner-file.txt",
          "Owner content"
        );

        expect(res.status).toBe(200);
        const data = await res.json();
        expect(data.message).toBe("File uploaded successfully");
      });
    });

    describe("Validation", () => {
      it("should return 400 if content is missing", async () => {
        const res = await client["tablo-data"][":tabloId"][":fileName"].$post(
          {
            param: { tabloId: "test_tablo_owner_private", fileName: "test.txt" },
            json: { contentType: "text/plain" },
          },
          {
            headers: { Authorization: `Bearer ${ownerUser.accessToken}` },
          }
        );

        expect(res.status).toBe(400);
        const data = await res.json();
        expect(data.error).toBe("Content is required");
      });
    });

    describe("Unauthenticated Access", () => {
      it("should deny unauthenticated upload attempt", async () => {
        const res = await client["tablo-data"][":tabloId"][":fileName"].$post({
          param: { tabloId: "test_tablo_owner_private", fileName: "test.txt" },
          json: { content: "test content" },
        });

        expect(res.status).toBe(401);
      });
    });
  });

  describe("DELETE /tablo-data/:tabloId/:fileName - Delete File (Admin or Uploader)", () => {
    // Helper function to delete file
    const deleteTabloFileRequest = async (
      user: TestUserData,
      // biome-ignore lint/suspicious/noExplicitAny: testClient requires any for dynamic route access
      client: any,
      tabloId: string,
      fileName: string
    ) => {
      return await client["tablo-data"][":tabloId"][":fileName"].$delete(
        {
          param: { tabloId, fileName },
        },
        {
          headers: { Authorization: `Bearer ${user.accessToken}` },
        }
      );
    };

    describe("Owner with Admin Access", () => {
      it("should allow owner to delete file from their own tablo", async () => {
        const res = await deleteTabloFileRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          "test-file.pdf"
        );

        expect(res.status).toBe(200);
        const data = await res.json();
        expect(data.message).toBe("File deleted successfully");
      });

      it("should allow owner to delete file from their shared tablo", async () => {
        const res = await deleteTabloFileRequest(
          ownerUser,
          client,
          "test_tablo_owner_shared",
          "test-file.pdf"
        );

        expect(res.status).toBe(200);
        const data = await res.json();
        expect(data.message).toBe("File deleted successfully");
      });

      it("should allow owner to delete file from temp's shared tablo when owner is admin member", async () => {
        const res = await deleteTabloFileRequest(
          ownerUser,
          client,
          "test_tablo_temp_shared_admin",
          "test-file.pdf"
        );

        expect(res.status).toBe(200);
      });
    });

    describe("Temp User Access (Member/Uploader Rules)", () => {
      it("should allow temp user to delete file from their own tablo", async () => {
        const res = await deleteTabloFileRequest(
          temporaryUser,
          client,
          "test_tablo_temp_private",
          "test-file.pdf"
        );

        expect(res.status).toBe(200);
      });

      it("should allow temp user to delete their own uploaded file in shared tablo", async () => {
        const res = await deleteTabloFileRequest(
          temporaryUser,
          client,
          "test_tablo_owner_shared",
          "temp-uploaded.pdf"
        );

        expect(res.status).toBe(200);
      });

      it("should deny temp user from deleting another user's file in shared tablo", async () => {
        const res = await deleteTabloFileRequest(
          temporaryUser,
          client,
          "test_tablo_owner_shared",
          "test-file.pdf"
        );

        expect(res.status).toBe(403);
      });
    });

    describe("Owner without Admin Access", () => {
      it("should deny owner from deleting file from temp's private tablo (no access)", async () => {
        const res = await deleteTabloFileRequest(
          ownerUser,
          client,
          "test_tablo_temp_private",
          "test-file.pdf"
        );

        // Owner has no access to temp's private tablo
        expect(res.status).toBe(403);
      });

      it("should deny owner from deleting file from temp's second private tablo (no access)", async () => {
        const res = await deleteTabloFileRequest(
          ownerUser,
          client,
          "test_tablo_temp_private_2",
          "test-file.pdf"
        );

        // Owner has no access to temp's private tablo
        expect(res.status).toBe(403);
      });
    });

    describe("Unauthenticated Access", () => {
      it("should deny unauthenticated deletion attempt", async () => {
        const res = await client["tablo-data"][":tabloId"][":fileName"].$delete({
          param: { tabloId: "test_tablo_owner_private", fileName: "test-file.pdf" },
        });

        expect(res.status).toBe(401);
      });
    });

    describe("Non-existent Resources", () => {
      it("should handle non-existent tablo deletion attempt", async () => {
        const res = await deleteTabloFileRequest(
          ownerUser,
          client,
          "non_existent_tablo",
          "test-file.pdf"
        );

        // Non-existent tablo returns 403 (forbidden)
        expect(res.status).toBe(403);
      });

      it("should successfully attempt to delete non-existent file from valid tablo", async () => {
        const res = await deleteTabloFileRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          "non-existent-file.pdf"
        );

        // S3 delete succeeds even if file doesn't exist (idempotent)
        expect(res.status).toBe(200);
      });
    });
  });

  // ============================================
  // FOLDER ENDPOINT TESTS
  // ============================================

  describe("GET /tablo-data/:tabloId/folders - Get Folders (Member Access)", () => {
    // Helper function to get folders
    const getFoldersRequest = async (
      user: TestUserData,
      // biome-ignore lint/suspicious/noExplicitAny: testClient requires any for dynamic route access
      client: any,
      tabloId: string
    ) => {
      return await client["tablo-data"][":tabloId"]["folders"].$get(
        { param: { tabloId } },
        { headers: { Authorization: `Bearer ${user.accessToken}` } }
      );
    };

    describe("Owner Access", () => {
      it("should allow owner to get folders from their own tablo", async () => {
        const res = await getFoldersRequest(ownerUser, client, "test_tablo_owner_private");

        expect(res.status).toBe(200);
        const data = await res.json();
        expect(data.folders).toEqual([]);
        expect(data.version).toBe(1);
      });

      it("should allow owner to get folders from their shared tablo", async () => {
        const res = await getFoldersRequest(ownerUser, client, "test_tablo_owner_shared");

        expect(res.status).toBe(200);
      });
    });

    describe("Temp User Access", () => {
      it("should allow temp user to get folders from owner's shared tablo", async () => {
        const res = await getFoldersRequest(temporaryUser, client, "test_tablo_owner_shared");

        expect(res.status).toBe(200);
      });

      it("should deny temp user access to owner's private tablo folders", async () => {
        const res = await getFoldersRequest(temporaryUser, client, "test_tablo_owner_private");

        expect(res.status).toBe(403);
      });
    });

    describe("Unauthenticated Access", () => {
      it("should deny unauthenticated access to folders", async () => {
        const res = await client["tablo-data"][":tabloId"]["folders"].$get({
          param: { tabloId: "test_tablo_owner_private" },
        });

        expect(res.status).toBe(401);
      });
    });
  });

  describe("POST /tablo-data/:tabloId/folders - Create Folder (Admin Only)", () => {
    // Helper function to create folder
    const createFolderRequest = async (
      user: TestUserData,
      // biome-ignore lint/suspicious/noExplicitAny: testClient requires any for dynamic route access
      client: any,
      tabloId: string,
      name: string,
      description?: string
    ) => {
      return await client["tablo-data"][":tabloId"]["folders"].$post(
        { param: { tabloId }, json: { name, description } },
        { headers: { Authorization: `Bearer ${user.accessToken}` } }
      );
    };

    describe("Owner with Admin Access", () => {
      it("should allow owner to create folder in their own tablo", async () => {
        const res = await createFolderRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          "My Folder",
          "Test description"
        );

        expect(res.status).toBe(200);
        const data = await res.json();
        expect(data.message).toBe("Folder created successfully");
        expect(data.folder.name).toBe("My Folder");
        expect(data.folder.description).toBe("Test description");
        expect(data.folder.id).toMatch(/^folder-/);
      });

      it("should allow owner to create folder without description", async () => {
        const res = await createFolderRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          "Folder Without Description"
        );

        expect(res.status).toBe(200);
        const data = await res.json();
        expect(data.folder.name).toBe("Folder Without Description");
        expect(data.folder.description).toBeUndefined();
      });
    });

    describe("Validation", () => {
      it("should return 400 if folder name is missing", async () => {
        const res = await client["tablo-data"][":tabloId"]["folders"].$post(
          { param: { tabloId: "test_tablo_owner_private" }, json: {} },
          { headers: { Authorization: `Bearer ${ownerUser.accessToken}` } }
        );

        expect(res.status).toBe(400);
        const data = await res.json();
        expect(data.error).toBe("Folder name is required");
      });

      it("should return 400 if folder name is empty string", async () => {
        const res = await createFolderRequest(ownerUser, client, "test_tablo_owner_private", "   ");

        expect(res.status).toBe(400);
        const data = await res.json();
        expect(data.error).toBe("Folder name is required");
      });

      it("should return 400 for duplicate folder names", async () => {
        // Create first folder
        await createFolderRequest(ownerUser, client, "test_tablo_owner_private", "Duplicate Name");

        // Try to create folder with same name
        const res = await createFolderRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          "duplicate name" // Case insensitive check
        );

        expect(res.status).toBe(400);
        const data = await res.json();
        expect(data.error).toBe("A folder with this name already exists");
      });
    });

    describe("Temp User - Blocked by regularUserCheck", () => {
      it("should deny temp user from creating folder (regularUserCheck)", async () => {
        const res = await createFolderRequest(
          temporaryUser,
          client,
          "test_tablo_temp_private",
          "Temp Folder"
        );

        // Temporary users are blocked by regularUserCheck middleware
        expect(res.status).toBe(401);
      });
    });

    describe("Unauthenticated Access", () => {
      it("should deny unauthenticated folder creation", async () => {
        const res = await client["tablo-data"][":tabloId"]["folders"].$post({
          param: { tabloId: "test_tablo_owner_private" },
          json: { name: "Test Folder" },
        });

        expect(res.status).toBe(401);
      });
    });
  });

  describe("PUT /tablo-data/:tabloId/folders/:folderId - Update Folder (Admin Only)", () => {
    // Helper function to update folder
    const updateFolderRequest = async (
      user: TestUserData,
      // biome-ignore lint/suspicious/noExplicitAny: testClient requires any for dynamic route access
      client: any,
      tabloId: string,
      folderId: string,
      name?: string,
      description?: string
    ) => {
      return await client["tablo-data"][":tabloId"]["folders"][":folderId"].$put(
        { param: { tabloId, folderId }, json: { name, description } },
        { headers: { Authorization: `Bearer ${user.accessToken}` } }
      );
    };

    // Helper to create a folder and return its ID
    const createTestFolder = async (tabloId: string, name: string): Promise<string> => {
      const res = await client["tablo-data"][":tabloId"]["folders"].$post(
        { param: { tabloId }, json: { name } },
        { headers: { Authorization: `Bearer ${ownerUser.accessToken}` } }
      );
      const data = await res.json();
      return data.folder.id;
    };

    describe("Owner with Admin Access", () => {
      it("should allow owner to update folder name", async () => {
        const folderId = await createTestFolder("test_tablo_owner_private", "Original Name");

        const res = await updateFolderRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          folderId,
          "Updated Name"
        );

        expect(res.status).toBe(200);
        const data = await res.json();
        expect(data.message).toBe("Folder updated successfully");
        expect(data.folder.name).toBe("Updated Name");
      });

      it("should allow owner to update folder description", async () => {
        const folderId = await createTestFolder("test_tablo_owner_private", "Test Folder");

        const res = await updateFolderRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          folderId,
          undefined,
          "New description"
        );

        expect(res.status).toBe(200);
        const data = await res.json();
        expect(data.folder.description).toBe("New description");
      });

      it("should allow owner to clear folder description", async () => {
        const folderId = await createTestFolder("test_tablo_owner_private", "Test Folder");

        // First set a description
        await updateFolderRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          folderId,
          undefined,
          "Some description"
        );

        // Then clear it
        const res = await updateFolderRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          folderId,
          undefined,
          ""
        );

        expect(res.status).toBe(200);
        const data = await res.json();
        expect(data.folder.description).toBeUndefined();
      });
    });

    describe("Validation", () => {
      it("should return 404 for non-existent folder", async () => {
        const res = await updateFolderRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          "non-existent-folder-id",
          "New Name"
        );

        expect(res.status).toBe(404);
        const data = await res.json();
        expect(data.error).toBe("Folder not found");
      });

      it("should return 400 for duplicate folder names on update", async () => {
        const folderId1 = await createTestFolder("test_tablo_owner_private", "Folder One");
        await createTestFolder("test_tablo_owner_private", "Folder Two");

        // Try to rename folder 1 to folder 2's name
        const res = await updateFolderRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          folderId1,
          "Folder Two"
        );

        expect(res.status).toBe(400);
        const data = await res.json();
        expect(data.error).toBe("A folder with this name already exists");
      });
    });

    describe("Temp User - Blocked by regularUserCheck", () => {
      it("should deny temp user from updating folder (regularUserCheck)", async () => {
        const res = await updateFolderRequest(
          temporaryUser,
          client,
          "test_tablo_temp_private",
          "some-folder-id",
          "New Name"
        );

        expect(res.status).toBe(401);
      });
    });

    describe("Unauthenticated Access", () => {
      it("should deny unauthenticated folder update", async () => {
        const res = await client["tablo-data"][":tabloId"]["folders"][":folderId"].$put({
          param: { tabloId: "test_tablo_owner_private", folderId: "some-id" },
          json: { name: "New Name" },
        });

        expect(res.status).toBe(401);
      });
    });
  });

  describe("DELETE /tablo-data/:tabloId/folders/:folderId - Delete Folder (Admin Only)", () => {
    // Helper function to delete folder
    const deleteFolderRequest = async (
      user: TestUserData,
      // biome-ignore lint/suspicious/noExplicitAny: testClient requires any for dynamic route access
      client: any,
      tabloId: string,
      folderId: string
    ) => {
      return await client["tablo-data"][":tabloId"]["folders"][":folderId"].$delete(
        { param: { tabloId, folderId } },
        { headers: { Authorization: `Bearer ${user.accessToken}` } }
      );
    };

    // Helper to create a folder and return its ID
    const createTestFolder = async (tabloId: string, name: string): Promise<string> => {
      const res = await client["tablo-data"][":tabloId"]["folders"].$post(
        { param: { tabloId }, json: { name } },
        { headers: { Authorization: `Bearer ${ownerUser.accessToken}` } }
      );
      const data = await res.json();
      return data.folder.id;
    };

    describe("Owner with Admin Access", () => {
      it("should allow owner to delete folder from their own tablo", async () => {
        const folderId = await createTestFolder("test_tablo_owner_private", "To Delete");

        const res = await deleteFolderRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          folderId
        );

        expect(res.status).toBe(200);
        const data = await res.json();
        expect(data.message).toBe("Folder deleted successfully");
        expect(data.folder.name).toBe("To Delete");
      });
    });

    describe("Validation", () => {
      it("should return 404 for non-existent folder", async () => {
        const res = await deleteFolderRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          "non-existent-folder-id"
        );

        expect(res.status).toBe(404);
        const data = await res.json();
        expect(data.error).toBe("Folder not found");
      });
    });

    describe("Temp User - Blocked by regularUserCheck", () => {
      it("should deny temp user from deleting folder (regularUserCheck)", async () => {
        const res = await deleteFolderRequest(
          temporaryUser,
          client,
          "test_tablo_temp_private",
          "some-folder-id"
        );

        expect(res.status).toBe(401);
      });
    });

    describe("Unauthenticated Access", () => {
      it("should deny unauthenticated folder deletion", async () => {
        const res = await client["tablo-data"][":tabloId"]["folders"][":folderId"].$delete({
          param: { tabloId: "test_tablo_owner_private", folderId: "some-id" },
        });

        expect(res.status).toBe(401);
      });
    });
  });

  // ============================================
  // NESTED FILE PATH TESTS (/:tabloId/file/:path)
  // ============================================

  describe("Nested File Path Routes (/file/:path)", () => {
    // Helper function to get file with nested path
    const getNestedFileRequest = async (
      user: TestUserData,
      // biome-ignore lint/suspicious/noExplicitAny: testClient requires any for dynamic route access
      client: any,
      tabloId: string,
      filePath: string
    ) => {
      return await client["tablo-data"][":tabloId"]["file"][":path"].$get(
        { param: { tabloId, path: filePath } },
        { headers: { Authorization: `Bearer ${user.accessToken}` } }
      );
    };

    // Helper function to post file with nested path
    const postNestedFileRequest = async (
      user: TestUserData,
      // biome-ignore lint/suspicious/noExplicitAny: testClient requires any for dynamic route access
      client: any,
      tabloId: string,
      filePath: string,
      content: string
    ) => {
      return await client["tablo-data"][":tabloId"]["file"][":path"].$post(
        { param: { tabloId, path: filePath }, json: { content, contentType: "text/plain" } },
        { headers: { Authorization: `Bearer ${user.accessToken}` } }
      );
    };

    // Helper function to delete file with nested path
    const deleteNestedFileRequest = async (
      user: TestUserData,
      // biome-ignore lint/suspicious/noExplicitAny: testClient requires any for dynamic route access
      client: any,
      tabloId: string,
      filePath: string
    ) => {
      return await client["tablo-data"][":tabloId"]["file"][":path"].$delete(
        { param: { tabloId, path: filePath } },
        { headers: { Authorization: `Bearer ${user.accessToken}` } }
      );
    };

    describe("GET /tablo-data/:tabloId/file/:path - Get File with Nested Path", () => {
      it("should allow owner to get file with nested path", async () => {
        const res = await getNestedFileRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          "folder-123/document.pdf"
        );

        expect(res.status).toBe(200);
        const data = await res.json();
        expect(data.fileName).toBe("folder-123/document.pdf");
        expect(data.content).toBe("test file content");
      });

      it("should allow owner to get file with deeply nested path", async () => {
        const res = await getNestedFileRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          "folder-123/subfolder/deep/file.txt"
        );

        expect(res.status).toBe(200);
        const data = await res.json();
        expect(data.fileName).toBe("folder-123/subfolder/deep/file.txt");
      });

      it("should allow member to get nested file from shared tablo", async () => {
        const res = await getNestedFileRequest(
          temporaryUser,
          client,
          "test_tablo_owner_shared",
          "folder-456/report.pdf"
        );

        expect(res.status).toBe(200);
      });

      it("should deny access to nested file in private tablo", async () => {
        const res = await getNestedFileRequest(
          temporaryUser,
          client,
          "test_tablo_owner_private",
          "folder-123/secret.pdf"
        );

        expect(res.status).toBe(403);
      });

      it("should deny unauthenticated access to nested file", async () => {
        const res = await client["tablo-data"][":tabloId"]["file"][":path"].$get({
          param: { tabloId: "test_tablo_owner_private", path: "folder/file.txt" },
        });

        expect(res.status).toBe(401);
      });
    });

    describe("POST /tablo-data/:tabloId/file/:path - Upload File with Nested Path", () => {
      it("should allow owner to upload file with nested path", async () => {
        const res = await postNestedFileRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          "folder-123/new-document.pdf",
          "Document content"
        );

        expect(res.status).toBe(200);
        const data = await res.json();
        expect(data.message).toBe("File uploaded successfully");
        expect(data.fileName).toBe("folder-123/new-document.pdf");
      });

      it("should allow member to upload file with nested path to shared tablo", async () => {
        const res = await postNestedFileRequest(
          temporaryUser,
          client,
          "test_tablo_owner_shared",
          "folder-789/upload.txt",
          "Uploaded content"
        );

        expect(res.status).toBe(200);
      });

      it("should deny member from uploading nested file to private tablo", async () => {
        const res = await postNestedFileRequest(
          temporaryUser,
          client,
          "test_tablo_owner_private",
          "folder-123/unauthorized.txt",
          "Should fail"
        );

        expect(res.status).toBe(403);
      });

      it("should deny unauthenticated nested file upload", async () => {
        const res = await client["tablo-data"][":tabloId"]["file"][":path"].$post({
          param: { tabloId: "test_tablo_owner_private", path: "folder/file.txt" },
          json: { content: "test" },
        });

        expect(res.status).toBe(401);
      });
    });

    describe("DELETE /tablo-data/:tabloId/file/:path - Delete File with Nested Path (Admin or Uploader)", () => {
      it("should allow admin to delete file with nested path", async () => {
        const res = await deleteNestedFileRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          "folder-123/to-delete.pdf"
        );

        expect(res.status).toBe(200);
        const data = await res.json();
        expect(data.message).toBe("File deleted successfully");
        expect(data.fileName).toBe("folder-123/to-delete.pdf");
      });

      it("should allow admin to delete deeply nested file", async () => {
        const res = await deleteNestedFileRequest(
          ownerUser,
          client,
          "test_tablo_owner_private",
          "folder-123/level2/level3/deep-file.txt"
        );

        expect(res.status).toBe(200);
      });

      it("should allow temp user to delete nested file from their own tablo", async () => {
        const res = await deleteNestedFileRequest(
          temporaryUser,
          client,
          "test_tablo_temp_private",
          "folder-123/file.pdf"
        );

        expect(res.status).toBe(200);
      });

      it("should allow admin member to delete nested file in shared tablo", async () => {
        const res = await deleteNestedFileRequest(
          ownerUser,
          client,
          "test_tablo_temp_shared_admin",
          "folder/file.pdf"
        );

        expect(res.status).toBe(200);
      });

      it("should deny unauthenticated nested file deletion", async () => {
        const res = await client["tablo-data"][":tabloId"]["file"][":path"].$delete({
          param: { tabloId: "test_tablo_owner_private", path: "folder/file.txt" },
        });

        expect(res.status).toBe(401);
      });
    });
  });
});
