import { describe, expect, it, vi } from 'vitest';

import { PicloudClient } from '../src/index.js';
import { jsonResponse, lastUrl, type FetchArgs } from './helpers.js';

describe('auth', () => {
  it('login POSTs credentials and stores the returned token', async () => {
    const fetchMock = vi.fn(async (_u: FetchArgs[0], _i?: FetchArgs[1]) =>
      jsonResponse({ token: 'session-abc' })
    );
    const client = new PicloudClient({ baseURL: 'https://api.test', fetch: fetchMock });

    const token = await client.auth.login('alice@example.com', 'pw');
    expect(token).toBe('session-abc');
    expect(client.auth.token).toBe('session-abc');
    expect(lastUrl(fetchMock)).toBe('https://api.test/api/auth/login');

    const init = fetchMock.mock.calls[0]?.[1];
    expect(JSON.parse(String(init?.body))).toEqual({
      email: 'alice@example.com',
      password: 'pw'
    });
  });

  it('logout clears the stored token', async () => {
    const fetchMock = vi.fn(async (_u: FetchArgs[0], _i?: FetchArgs[1]) => jsonResponse({}));
    const client = new PicloudClient({ baseURL: 'https://api.test', fetch: fetchMock });
    client.auth.setToken('existing');
    await client.auth.logout();
    expect(client.auth.token).toBeNull();
  });

  it('provider returns the current token for getAuthToken wiring', async () => {
    const fetchMock = vi.fn(async (_u: FetchArgs[0], _i?: FetchArgs[1]) =>
      jsonResponse({ token: 't' })
    );
    const client = new PicloudClient({ baseURL: 'https://api.test', fetch: fetchMock });
    await client.auth.login('a@b.c', 'pw');
    expect(client.auth.provider()).toBe('t');
  });
});
