/**
 * Unit test for the transport factory + S3 endpoint parser
 * (`src/lib/services/backup-destinations/`).
 */

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

import {
  buildTransport,
  FilesystemTransport,
  parseS3Endpoint,
  S3Transport,
  SftpTransport,
} from '@/lib/services/backup-destinations';

describe('buildTransport', () => {
  it('builds the right transport per type', () => {
    expect(buildTransport('filesystem', { directory: '/x' })).toBeInstanceOf(FilesystemTransport);
    expect(buildTransport('sftp', { host: 'h', username: 'u', remoteDir: '/d' })).toBeInstanceOf(
      SftpTransport,
    );
    expect(
      buildTransport('s3', { endpoint: 'h', bucket: 'b', accessKey: 'a', secretKey: 's' }),
    ).toBeInstanceOf(S3Transport);
  });

  it('throws on an unknown type', () => {
    // @ts-expect-error testing the runtime guard
    expect(() => buildTransport('ftp', {})).toThrow(/Unknown backup destination type/);
  });
});

describe('parseS3Endpoint', () => {
  it('parses an https URL into host + ssl', () => {
    expect(parseS3Endpoint('https://s3.eu-central.example.com', {})).toEqual({
      endPoint: 's3.eu-central.example.com',
      useSSL: true,
    });
  });

  it('parses an http URL with a port', () => {
    expect(parseS3Endpoint('http://localhost:9000', {})).toEqual({
      endPoint: 'localhost',
      port: 9000,
      useSSL: false,
    });
  });

  it('treats a bare host as ssl-by-default', () => {
    expect(parseS3Endpoint('s3.amazonaws.com', {})).toEqual({
      endPoint: 's3.amazonaws.com',
      useSSL: true,
    });
  });

  it('honours explicit useSSL=false on a bare host', () => {
    expect(parseS3Endpoint('minio.internal', { useSSL: false, port: 9000 })).toEqual({
      endPoint: 'minio.internal',
      port: 9000,
      useSSL: false,
    });
  });
});
