import { describe, it, expect, beforeEach } from 'vitest';
import { isValidReturnUrl } from '../config/billing.config';

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

  beforeEach(() => {
    process.env = { ...originalEnv, ALLOWED_RETURN_URL_ORIGINS: 'https://app.shieldai.com,shieldai://' };
  });

  it('accepts allowed web origin', () => {
    expect(isValidReturnUrl('https://app.shieldai.com/account')).toBe(true);
  });

  it('accepts allowed web origin with path and query params', () => {
    expect(isValidReturnUrl('https://app.shieldai.com/settings?tab=billing')).toBe(true);
  });

  it('accepts custom app scheme', () => {
    expect(isValidReturnUrl('shieldai://portal-return')).toBe(true);
  });

  it('rejects attacker-controlled domain', () => {
    expect(isValidReturnUrl('https://evil.com/phish')).toBe(false);
  });

  it('rejects subdomain of allowed origin', () => {
    expect(isValidReturnUrl('https://evil-app.shieldai.com/hack')).toBe(false);
  });

  it('rejects domain that contains allowed origin as substring', () => {
    expect(isValidReturnUrl('https://notapp.shieldai.com/hack')).toBe(false);
  });

  it('rejects domain that has allowed origin as prefix (substring attack)', () => {
    expect(isValidReturnUrl('https://app.shieldai.com.evil.com/hack')).toBe(false);
  });

  it('rejects malformed URLs', () => {
    expect(isValidReturnUrl('not-a-url')).toBe(false);
    expect(isValidReturnUrl('')).toBe(false);
  });

  it('rejects javascript protocol', () => {
    expect(isValidReturnUrl('javascript:alert(1)')).toBe(false);
  });

  it('rejects data protocol', () => {
    expect(isValidReturnUrl('data:text/html,<script>alert(1)</script>')).toBe(false);
  });

  it('rejects protocol-relative URLs', () => {
    expect(isValidReturnUrl('//evil.com/steal')).toBe(false);
  });

  it('rejects URL with allowed origin in query string', () => {
    expect(isValidReturnUrl('https://evil.com/?redirect=https://app.shieldai.com')).toBe(false);
  });
});
