/**
 * Missing Dependencies Detection Test
 *
 * This test ensures all imports in the codebase can be resolved
 * and prevents compilation errors due to missing dependencies.
 *
 * Created: 2025-11-18
 * Issue: @headlessui/react was missing, causing compilation failure
 */

import { execSync } from "child_process";
import * as fs from "fs";
import * as path from "path";

describe("Dependency Resolution Tests", () => {
  describe("Critical Dependencies", () => {
    const criticalDependencies = [
      "@headlessui/react",
      "next",
      "react",
      "react-dom",
      "next-auth",
      "@prisma/client",
      "tailwindcss",
      "typescript",
    ];

    criticalDependencies.forEach((dep) => {
      it(`should have ${dep} installed`, () => {
        const packageJson = JSON.parse(
          fs.readFileSync(path.join(process.cwd(), "package.json"), "utf-8"),
        );

        const isInstalled =
          packageJson.dependencies?.[dep] || packageJson.devDependencies?.[dep];

        expect(isInstalled).toBeTruthy();
      });
    });
  });

  describe("Import Resolution", () => {
    it("should be able to resolve @headlessui/react imports", () => {
      expect(() => {
        require.resolve("@headlessui/react");
      }).not.toThrow();
    });

    it("should be able to resolve all Headless UI components used in the app", () => {
      const headlessUIComponents = [
        "@headlessui/react/Menu",
        "@headlessui/react/Dialog",
        "@headlessui/react/Transition",
        "@headlessui/react/Tab",
      ];

      headlessUIComponents.forEach((component) => {
        expect(() => {
          // Check if the package can be required
          require.resolve("@headlessui/react");
        }).not.toThrow();
      });
    });
  });

  describe("TypeScript Compilation", () => {
    it("should compile AccountDropdown component without errors", () => {
      const componentPath = path.join(
        process.cwd(),
        "components/dashboard/AccountDropdown.tsx",
      );

      expect(fs.existsSync(componentPath)).toBe(true);

      // Check if the file contains the problematic import
      const content = fs.readFileSync(componentPath, "utf-8");
      expect(content).toContain("@headlessui/react");
    });

    it("should compile AccountSettingsModal component without errors", () => {
      const componentPath = path.join(
        process.cwd(),
        "components/dashboard/AccountSettingsModal.tsx",
      );

      expect(fs.existsSync(componentPath)).toBe(true);

      const content = fs.readFileSync(componentPath, "utf-8");
      expect(content).toContain("@headlessui/react");
    });
  });

  describe("Build Safety Check", () => {
    it("should list all package.json dependencies and devDependencies", () => {
      const packageJson = JSON.parse(
        fs.readFileSync(path.join(process.cwd(), "package.json"), "utf-8"),
      );

      expect(packageJson.dependencies).toBeDefined();
      expect(packageJson.devDependencies).toBeDefined();
      expect(Object.keys(packageJson.dependencies).length).toBeGreaterThan(0);
    });

    it("should have node_modules/@headlessui directory", () => {
      const headlessUIPath = path.join(
        process.cwd(),
        "node_modules/@headlessui",
      );
      expect(fs.existsSync(headlessUIPath)).toBe(true);
    });
  });

  describe("Component Import Analysis", () => {
    const componentsToCheck = [
      "components/dashboard/AccountDropdown.tsx",
      "components/dashboard/AccountSettingsModal.tsx",
    ];

    componentsToCheck.forEach((componentPath) => {
      it(`should have all imports resolvable in ${componentPath}`, () => {
        const fullPath = path.join(process.cwd(), componentPath);

        if (!fs.existsSync(fullPath)) {
          console.warn(`Component not found: ${componentPath}`);
          return;
        }

        const content = fs.readFileSync(fullPath, "utf-8");

        // Extract all imports from the file
        const importRegex = /from ['"]([^'"]+)['"]/g;
        const imports = [];
        let match;

        while ((match = importRegex.exec(content)) !== null) {
          imports.push(match[1]);
        }

        // Check critical external packages
        const externalImports = imports.filter(
          (imp) => !imp.startsWith(".") && !imp.startsWith("@/"),
        );

        externalImports.forEach((imp) => {
          const packageName = imp.startsWith("@")
            ? imp.split("/").slice(0, 2).join("/")
            : imp.split("/")[0];

          const packageJson = JSON.parse(
            fs.readFileSync(path.join(process.cwd(), "package.json"), "utf-8"),
          );

          const isInstalled =
            packageJson.dependencies?.[packageName] ||
            packageJson.devDependencies?.[packageName];

          expect(isInstalled).toBeTruthy();
        });
      });
    });
  });
});

describe("Pre-Deployment Checks", () => {
  it("should have a valid package-lock.json file", () => {
    const lockPath = path.join(process.cwd(), "package-lock.json");
    expect(fs.existsSync(lockPath)).toBe(true);

    const lockContent = fs.readFileSync(lockPath, "utf-8");
    expect(() => JSON.parse(lockContent)).not.toThrow();
  });

  it("should not have any obvious missing peer dependencies", () => {
    const packageJson = JSON.parse(
      fs.readFileSync(path.join(process.cwd(), "package.json"), "utf-8"),
    );

    // Check for common peer dependency issues
    if (packageJson.dependencies?.["next-auth"]) {
      expect(
        packageJson.dependencies?.["next"] ||
          packageJson.devDependencies?.["next"],
      ).toBeTruthy();
    }

    if (packageJson.dependencies?.["@headlessui/react"]) {
      expect(
        packageJson.dependencies?.["react"] ||
          packageJson.devDependencies?.["react"],
      ).toBeTruthy();
    }
  });
});
