import { EventEmitter } from "events";

// Mock for node modules that interact with the file system
jest.mock("fs", () => ({
  ...jest.requireActual("fs"),
  existsSync: jest.fn().mockReturnValue(true),
  mkdirSync: jest.fn().mockReturnValue(undefined),
  promises: {
    mkdir: jest.fn().mockResolvedValue(undefined),
    access: jest.fn().mockResolvedValue(undefined),
    stat: jest.fn().mockResolvedValue({
      isFile: () => true,
      size: 1024,
    }),
  },
}));

// Mock for path module functions
jest.mock("path", () => ({
  ...jest.requireActual("path"),
  join: jest.fn((...paths) => paths.join("/")),
  resolve: jest.fn((...paths) => paths.join("/")),
}));

// Mock for child_process
jest.mock("child_process", () => {
  const MockChildProcess = class extends EventEmitter {
    public pid = 12345;
    public stdin = new EventEmitter();
    public stdout = new EventEmitter();
    public stderr = new EventEmitter();
    public killed = false;

    kill() {
      this.killed = true;
      this.emit("close", 0);
      return true;
    }
  };

  return {
    exec: jest.fn((command, callback) => {
      callback(null, "success", "");
      return new MockChildProcess();
    }),
    execFileSync: jest.fn((command, args) => {
      if (args.includes("-list_devices") && args.includes("true")) {
        return Buffer.from(`
          [AVFoundation input device @ 0x7f8c7f5c5000] AVFoundation video devices:
          [AVFoundation input device @ 0x7f8c7f5c5000] [0] FaceTime HD Camera
          [AVFoundation input device @ 0x7f8c7f5c5000] [1] External Camera
          [AVFoundation input device @ 0x7f8c7f5c5000] AVFoundation audio devices:
          [AVFoundation input device @ 0x7f8c7f5c5000] [0] Built-in Microphone
          [AVFoundation input device @ 0x7f8c7f5c5000] [1] External Microphone
        `);
      }
      return Buffer.from("");
    }),
    spawn: jest.fn(() => {
      const proc = new MockChildProcess();
      setTimeout(() => {
        proc.emit("spawn");
      }, 10);
      return proc;
    }),
  };
});
