import {
  driveConnectUrl,
  driveSyncProgressPercent,
  formatDriveSyncError,
  parseResourceIdsInput,
} from './drive';

describe('driveSyncProgressPercent', () => {
  it('returns null when total is unknown', () => {
    expect(driveSyncProgressPercent({ id: 1, provider: 'google', sync_total: 0 })).toBeNull();
  });

  it('computes rounded percent from processed/total', () => {
    expect(
      driveSyncProgressPercent({
        id: 1,
        provider: 'google',
        sync_total: 4,
        sync_processed: 1,
      })
    ).toBe(25);
  });
});

describe('parseResourceIdsInput', () => {
  it('splits comma and newline separated ids and trims whitespace', () => {
    expect(parseResourceIdsInput('abc, def\nghi ,, ')).toEqual(['abc', 'def', 'ghi']);
  });

  it('returns an empty array for blank input', () => {
    expect(parseResourceIdsInput('   ')).toEqual([]);
  });
});

describe('formatDriveSyncError', () => {
  it('returns a fallback when empty', () => {
    expect(formatDriveSyncError('')).toMatch(/Drive sync failed/);
  });

  it('truncates long provider error payloads', () => {
    const long = 'x'.repeat(400);
    const formatted = formatDriveSyncError(long, 50);
    expect(formatted.length).toBeLessThanOrEqual(51);
    expect(formatted.endsWith('…')).toBe(true);
  });
});

describe('driveConnectUrl', () => {
  const originalEnv = process.env.REACT_APP_BACKEND_REST_API_BASE_URL;

  beforeAll(() => {
    process.env.REACT_APP_BACKEND_REST_API_BASE_URL = 'https://api.example.com/';
  });

  afterAll(() => {
    process.env.REACT_APP_BACKEND_REST_API_BASE_URL = originalEnv;
  });

  it('builds a personal drive-link url', () => {
    expect(driveConnectUrl('google', 'link_drive')).toBe(
      'https://api.example.com/auth/oauth/google/start/?intent=link_drive'
    );
  });

  it('builds a company drive-link url', () => {
    expect(driveConnectUrl('microsoft', 'link_company_drive')).toBe(
      'https://api.example.com/auth/oauth/microsoft/start/?intent=link_company_drive'
    );
  });
});
