// SPDX-License-Identifier: GPL-3.0-or-later

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { getCredentials } from './api';
import type { CredentialsResponse } from './api';

describe('getCredentials', () => {
  const mockFetch = vi.fn();
  const originalFetch = global.fetch;

  beforeEach(() => {
    global.fetch = mockFetch;
  });

  afterEach(() => {
    global.fetch = originalFetch;
    mockFetch.mockReset();
  });

  it('returns S3 credentials when available', async () => {
    const mockResponse: CredentialsResponse = {
      access_key_id: 'pb_abcdef1234567890abc',
      bucket_name: 'pb-abcdef1234567890abc',
      has_credentials: true,
      data_backend: 's3',
    };

    mockFetch.mockResolvedValueOnce({
      ok: true,
      text: async () => JSON.stringify(mockResponse),
      json: async () => mockResponse,
    });

    const result = await getCredentials();

    expect(result.access_key_id).toBe('pb_abcdef1234567890abc');
    expect(result.bucket_name).toBe('pb-abcdef1234567890abc');
    expect(result.has_credentials).toBe(true);
    expect(result.data_backend).toBe('s3');
  });

  it('returns legacy REST when no S3 credentials', async () => {
    const mockResponse: CredentialsResponse = {
      access_key_id: '',
      bucket_name: '',
      has_credentials: false,
      data_backend: 'rest',
    };

    mockFetch.mockResolvedValueOnce({
      ok: true,
      text: async () => JSON.stringify(mockResponse),
      json: async () => mockResponse,
    });

    const result = await getCredentials();

    expect(result.has_credentials).toBe(false);
    expect(result.data_backend).toBe('rest');
  });

  it('throws on API error', async () => {
    mockFetch.mockResolvedValueOnce({
      ok: false,
      status: 500,
      statusText: 'Internal Server Error',
      json: async () => ({ error: 'internal error' }),
    });

    await expect(getCredentials()).rejects.toThrow();
  });

  it('calls correct endpoint', async () => {
    const mockResponse: CredentialsResponse = {
      access_key_id: '',
      bucket_name: '',
      has_credentials: false,
      data_backend: 'rest',
    };

    mockFetch.mockResolvedValueOnce({
      ok: true,
      text: async () => JSON.stringify(mockResponse),
      json: async () => mockResponse,
    });

    await getCredentials();

    expect(mockFetch).toHaveBeenCalledWith(
      '/api/v1/credentials',
      expect.objectContaining({
        headers: expect.objectContaining({
          'Content-Type': 'application/json',
        }),
      })
    );
  });
});
