import { describe, expect, it, vi } from 'vitest';
import { RestClient, RestError } from '../src/api/rest-client.js';

type Captured = { url: string; init: RequestInit };

function fakeFetch(response: { ok: boolean; status: number; body: unknown }, captured: Captured[]) {
  return vi.fn(async (url: string, init: RequestInit) => {
    captured.push({ url, init });
    return {
      ok: response.ok,
      status: response.status,
      json: async () => response.body,
    } as unknown as Response;
  }) as unknown as typeof fetch;
}

describe('RestClient', () => {
  it('appelle /api/v1/auth/me avec le header Bearer', async () => {
    const captured: Captured[] = [];
    const rest = new RestClient(
      { baseUrl: 'http://127.0.0.1:7317/', token: 'arb_secret' },
      fakeFetch({ ok: true, status: 200, body: { ok: true, tokenId: 't', tokenLabel: 'l', serverVersion: '1.8.0' } }, captured),
    );
    const me = await rest.me();
    expect(me.serverVersion).toBe('1.8.0');
    expect(captured[0]?.url).toBe('http://127.0.0.1:7317/api/v1/auth/me');
    const headers = captured[0]?.init.headers as Record<string, string>;
    expect(headers.Authorization).toBe('Bearer arb_secret');
  });

  it('normalise les erreurs serveur en RestError (code + status)', async () => {
    const rest = new RestClient(
      { baseUrl: 'http://127.0.0.1:7317', token: 'bad' },
      fakeFetch({ ok: false, status: 401, body: { error: { code: 'BAD_TOKEN', message: 'invalid token' } } }, []),
    );
    await expect(rest.me()).rejects.toMatchObject({ code: 'BAD_TOKEN', status: 401 });
    await expect(rest.me()).rejects.toBeInstanceOf(RestError);
  });

  it('encode les ids dans les chemins et envoie le corps JSON', async () => {
    const captured: Captured[] = [];
    const rest = new RestClient(
      { baseUrl: 'http://h:1', token: 't' },
      fakeFetch({ ok: true, status: 200, body: { worktree: {} } }, captured),
    );
    await rest.commitWorktree('repo id', { path: '/w', message: 'msg' });
    expect(captured[0]?.url).toBe('http://h:1/api/v1/repos/repo%20id/worktrees/commit');
    expect(captured[0]?.init.method).toBe('POST');
    expect(JSON.parse(String(captured[0]?.init.body))).toEqual({ path: '/w', message: 'msg' });
  });

  it('fetch/pull worktree : chemins et corps', async () => {
    const captured: Captured[] = [];
    const rest = new RestClient(
      { baseUrl: 'http://h:1', token: 't' },
      fakeFetch({ ok: true, status: 200, body: { worktree: {} } }, captured),
    );
    await rest.fetchWorktree('r', { path: '/w' });
    await rest.pullWorktree('r', { path: '/w', mode: 'rebase' });
    expect(captured[0]?.url).toBe('http://h:1/api/v1/repos/r/worktrees/fetch');
    expect(captured[1]?.url).toBe('http://h:1/api/v1/repos/r/worktrees/pull');
    expect(JSON.parse(String(captured[1]?.init.body))).toEqual({ path: '/w', mode: 'rebase' });
  });

  it('listSessions construit la query includeHidden/includeArchived', async () => {
    const captured: Captured[] = [];
    const rest = new RestClient(
      { baseUrl: 'http://h:1', token: 't' },
      fakeFetch({ ok: true, status: 200, body: { sessions: [] } }, captured),
    );
    await rest.listSessions();
    await rest.listSessions({ includeArchived: true });
    await rest.listSessions({ includeHidden: true, includeArchived: true });
    expect(captured[0]?.url).toBe('http://h:1/api/v1/sessions');
    expect(captured[1]?.url).toBe('http://h:1/api/v1/sessions?includeArchived=true');
    expect(captured[2]?.url).toBe('http://h:1/api/v1/sessions?includeHidden=true&includeArchived=true');
  });
});
