import { describe, expect, it } from 'vitest';
import { InvalidMediaBaseUrlError, publicBaseUrl, type MediaEnv } from './storage.js';

function env(baseUrl: string): MediaEnv {
  return { MEDIA_BUCKET: {} as MediaEnv['MEDIA_BUCKET'], MEDIA_PUBLIC_BASE_URL: baseUrl };
}

describe('publicBaseUrl', () => {
  it('throws InvalidMediaBaseUrlError for http:// URLs', () => {
    expect(() => publicBaseUrl(env('http://cdn.example'))).toThrow(InvalidMediaBaseUrlError);
  });

  it('throws InvalidMediaBaseUrlError for empty string', () => {
    expect(() => publicBaseUrl(env(''))).toThrow(InvalidMediaBaseUrlError);
  });

  it('throws InvalidMediaBaseUrlError for bare host', () => {
    expect(() => publicBaseUrl(env('cdn.example'))).toThrow(InvalidMediaBaseUrlError);
  });

  it('throws InvalidMediaBaseUrlError for scheme-only https:// (no host)', () => {
    expect(() => publicBaseUrl(env('https://'))).toThrow(InvalidMediaBaseUrlError);
  });

  it('returns trailing-slash-stripped origin for https:// URLs', () => {
    expect(publicBaseUrl(env('https://cdn.example'))).toBe('https://cdn.example');
    expect(publicBaseUrl(env('https://cdn.example/'))).toBe('https://cdn.example');
  });

  it('preserves CDN subpath and strips trailing slash', () => {
    expect(publicBaseUrl(env('https://cdn.example/media/'))).toBe('https://cdn.example/media');
  });
});
