jest.mock('discord.js', () => {
  const original = jest.requireActual('discord.js');
  const mockRest = {
    put: jest.fn().mockResolvedValue([{ length: 1 }]),
    setToken: jest.fn().mockReturnThis(),
  };
  return {
    ...original,
    REST: jest.fn(() => mockRest),
    Routes: {
      applicationCommands: jest.fn().mockReturnValue('/fake-route'),
    },
  };
});

jest.mock('fs', () => ({
  readdirSync: jest.fn(() => ['ping.js']),
}));
jest.mock('node:path', () => {
  const actual = jest.requireActual('node:path');
  return {
    ...actual,
    join: (...args) => args.join('/'),
    resolve: (...args) => args.join('/'),
  };
});

describe('deploy-commands.js', () => {
  let origEnv;
  beforeAll(() => {
    origEnv = { ...process.env };
    process.env.CLIENT_ID = '12345';
    process.env.DISCORD_TOKEN = 'token';
  });

  afterAll(() => {
    process.env = origEnv;
    jest.resetModules();
  });

  test('registers commands via REST API', async () => {
    const mockLogger = { info: jest.fn(), warn: jest.fn(), error: jest.fn() };
    jest.mock('../src/utils/logger', () => mockLogger);

    // Run the script
    await require('../deploy-commands.js');

    const { REST } = require('discord.js');
    expect(REST).toHaveBeenCalled();
    const restInstance = REST.mock.results[0].value;
    expect(restInstance.setToken).toHaveBeenCalledWith('token');
    expect(restInstance.put).toHaveBeenCalledWith('/fake-route', { body: expect.any(Array) });
    expect(mockLogger.info).toHaveBeenCalledWith(expect.stringContaining('Started refreshing'));
  });
});
