import { afterEach, describe, expect, test, vi } from 'vitest';

const load = async () => {
  vi.resetModules();
  process.env.SPOON_WORKER_TOKEN = 'test-worker-token';
  process.env.GITHUB_APP_ID = '123';
  process.env.GITHUB_APP_PRIVATE_KEY =
    '-----BEGIN PRIVATE KEY-----\ntest\n-----END PRIVATE KEY-----';
  vi.doMock('../../src/worker', () => ({ getTerminalWorkspace: () => null }));
  vi.doMock('../../src/user-container', () => ({
    acquireUserBox: vi.fn(),
  }));
  return await import('../../src/terminal');
};

describe('parseResizeMessage', () => {
  afterEach(() => vi.resetModules());

  test('parses and clamps a resize control frame', async () => {
    const { parseResizeMessage } = await load();
    const msg = Buffer.from(
      JSON.stringify({ type: 'resize', cols: 120, rows: 40 }),
    );
    expect(parseResizeMessage(msg, false)).toEqual({ cols: 120, rows: 40 });
  });

  test('returns null for binary input (raw keystrokes)', async () => {
    const { parseResizeMessage } = await load();
    expect(parseResizeMessage(Buffer.from([1, 2, 3]), true)).toBeNull();
  });

  test('returns null for non-resize JSON', async () => {
    const { parseResizeMessage } = await load();
    expect(
      parseResizeMessage(Buffer.from('{"type":"other"}'), false),
    ).toBeNull();
  });

  test('clamps out-of-range dimensions into [1,1000]', async () => {
    const { parseResizeMessage } = await load();
    const msg = Buffer.from(
      JSON.stringify({ type: 'resize', cols: 99999, rows: 0 }),
    );
    expect(parseResizeMessage(msg, false)).toEqual({ cols: 1000, rows: 1 });
  });
});
