import { describe, it, expect } from 'vitest';
import { SELF } from 'cloudflare:test';
import { healthRouter } from '../src/routes/health';
import type { Bindings, ExecutionContext } from '../src/types';

describe('GET /health — bundle_version 欄位', () => {
  it('無 ARCRUN_BUNDLE_VERSION 時省略該欄（老實例情境）', async () => {
    // wrangler.test.toml 不設此 var → health.ts 省略 bundle_version 欄位。
    // daemon 端讀不到該欄＝當作空字串＝判 stale，對老實例而言**這是正確行為**
    //（見 health.ts 檔頭註解）。此處驗「省略」而非「回空字串」，與實作對齊。
    const res = await SELF.fetch('http://localhost/health');
    const data = await res.json() as { ok: boolean; bundle_version?: string };
    expect(res.status).toBe(200);
    expect(data.ok).toBe(true);
    expect(data.bundle_version).toBeUndefined();
  });

  it('有 ARCRUN_BUNDLE_VERSION 時回其值（安裝器注入情境）', async () => {
    const fakeEnv = { ARCRUN_BUNDLE_VERSION: '2026-07-28/6d06162' } as unknown as Bindings;
    const res = await healthRouter.fetch(
      new Request('http://localhost/health'),
      fakeEnv,
      {} as ExecutionContext,
    );
    const data = await res.json() as { ok: boolean; bundle_version: string };
    expect(data.ok).toBe(true);
    expect(data.bundle_version).toBe('2026-07-28/6d06162');
  });

  // Arcrun#106：CLI 更新那條路會多烙一個 commit（版號＝發行頻道編號，commit＝真的部了哪份碼）。
  it('有 ARCRUN_BUNDLE_COMMIT 時一起回（acr update 注入情境）', async () => {
    const fakeEnv = {
      ARCRUN_BUNDLE_VERSION: '1.4.41',
      ARCRUN_BUNDLE_COMMIT: 'f87d0e92f49690253e7c89c5badc82a08eb5d21b',
    } as unknown as Bindings;
    const res = await healthRouter.fetch(
      new Request('http://localhost/health'),
      fakeEnv,
      {} as ExecutionContext,
    );
    const data = await res.json() as { bundle_version: string; bundle_commit: string };
    expect(data.bundle_version).toBe('1.4.41');
    expect(data.bundle_commit).toBe('f87d0e92f49690253e7c89c5badc82a08eb5d21b');
  });

  // 安裝器那條路沒有這個 var（回歸：不能因為多了新欄位就讓舊路徑多吐一個空字串出來）。
  it('沒 ARCRUN_BUNDLE_COMMIT 就省略該欄（安裝器路徑不受影響）', async () => {
    const fakeEnv = { ARCRUN_BUNDLE_VERSION: '1.4.41' } as unknown as Bindings;
    const res = await healthRouter.fetch(
      new Request('http://localhost/health'),
      fakeEnv,
      {} as ExecutionContext,
    );
    const data = await res.json() as { bundle_version: string; bundle_commit?: string };
    expect(data.bundle_version).toBe('1.4.41');
    expect(data.bundle_commit).toBeUndefined();
  });
});
