describe('Platform Paths — cross-platform path resolution', () => {
  const originalPlatform = process.platform;
  const originalEnv = { ...process.env };

  afterEach(() => {
    // Restore env
    process.env = { ...originalEnv };
    jest.resetModules();
  });

  function loadPaths() {
    return require('../platform-paths');
  }

  describe('default paths on current platform', () => {
    it('exports all required path properties', () => {
      const paths = loadPaths();
      expect(paths).toHaveProperty('caddyBase');
      expect(paths).toHaveProperty('caddySites');
      expect(paths).toHaveProperty('dockerData');
      expect(paths).toHaveProperty('caddyfile');
      expect(paths).toHaveProperty('caddyAdminUrl');
      expect(paths).toHaveProperty('servicesFile');
      expect(paths).toHaveProperty('configFile');
      expect(paths).toHaveProperty('dnsCredentialsFile');
      expect(paths).toHaveProperty('caCertDir');
      expect(paths).toHaveProperty('pkiRootCert');
      expect(paths).toHaveProperty('sitePath');
      expect(paths).toHaveProperty('appData');
      expect(paths).toHaveProperty('isWindows');
      expect(paths).toHaveProperty('isLinux');
    });

    it('sitePath returns path under caddySites', () => {
      const paths = loadPaths();
      const result = paths.sitePath('plex');
      expect(result).toContain('plex');
      const norm = p => p.replace(/\\/g, '/');
      expect(norm(result)).toContain(norm(paths.caddySites));
    });

    it('appData returns path under dockerData', () => {
      const paths = loadPaths();
      const result = paths.appData('radarr');
      expect(result).toContain('radarr');
      const norm = p => p.replace(/\\/g, '/');
      expect(norm(result)).toContain(norm(paths.dockerData));
    });
  });

  describe('environment variable overrides', () => {
    it('CADDY_BASE overrides caddyBase', () => {
      process.env.CADDY_BASE = '/custom/caddy';
      const paths = loadPaths();
      expect(paths.caddyBase).toBe('/custom/caddy');
    });

    it('DOCKER_DATA overrides dockerData', () => {
      process.env.DOCKER_DATA = '/custom/docker';
      const paths = loadPaths();
      expect(paths.dockerData).toBe('/custom/docker');
    });

    it('CADDYFILE_PATH overrides caddyfile', () => {
      process.env.CADDYFILE_PATH = '/custom/Caddyfile';
      const paths = loadPaths();
      expect(paths.caddyfile).toBe('/custom/Caddyfile');
    });

    it('CADDY_ADMIN_URL overrides caddyAdminUrl', () => {
      process.env.CADDY_ADMIN_URL = 'http://custom:9999';
      const paths = loadPaths();
      expect(paths.caddyAdminUrl).toBe('http://custom:9999');
    });

    it('SERVICES_FILE overrides servicesFile', () => {
      process.env.SERVICES_FILE = '/custom/services.json';
      const paths = loadPaths();
      expect(paths.servicesFile).toBe('/custom/services.json');
    });
  });

  describe('toDockerMountPath', () => {
    it('passes through Unix paths unchanged', () => {
      const paths = loadPaths();
      if (!paths.isWindows) {
        expect(paths.toDockerMountPath('/opt/dockerdata/plex')).toBe('/opt/dockerdata/plex');
      }
    });

    it('passes through non-drive-letter strings unchanged on any platform', () => {
      const paths = loadPaths();
      // Plain strings without drive letters should pass through unchanged
      expect(paths.toDockerMountPath('relative/path')).toBe('relative/path');
      expect(paths.toDockerMountPath('plainstring')).toBe('plainstring');
    });

    if (process.platform === 'win32') {
      it('converts Windows drive paths to Docker mount format', () => {
        const paths = loadPaths();
        expect(paths.toDockerMountPath('C:/caddy/Caddyfile')).toBe('//mnt/host/c/caddy/Caddyfile');
        expect(paths.toDockerMountPath('E:/dockerdata/plex')).toBe('//mnt/host/e/dockerdata/plex');
      });

      it('converts backslash paths', () => {
        const paths = loadPaths();
        expect(paths.toDockerMountPath('C:\\caddy\\Caddyfile')).toBe('//mnt/host/c/caddy/Caddyfile');
      });

      it('passes through already-converted paths', () => {
        const paths = loadPaths();
        expect(paths.toDockerMountPath('//mnt/host/c/foo')).toBe('//mnt/host/c/foo');
      });

      it('passes through Unix paths on Windows (container internal paths)', () => {
        const paths = loadPaths();
        expect(paths.toDockerMountPath('/app/services.json')).toBe('/app/services.json');
      });
    }
  });

  // ============================================================================
  // dataDir safety guard — DC-046 follow-up to DC-039. Catches the silent
  // failure mode where SERVICES_FILE isn't set as an env var and resolution
  // falls back to a path inside the Docker image layer.
  // ============================================================================
  describe('assertSafe (DC-046 follow-up to DC-039)', () => {
    if (process.platform !== 'linux') {
      it('is a no-op on non-Linux platforms (Windows uses different path tree)', () => {
        const paths = loadPaths();
        expect(() => paths.assertSafe({ mode: 'production' })).not.toThrow();
      });
      return;
    }

    it('throws when SERVICES_FILE unset and CADDY_BASE resolves to /etc/dashcaddy', () => {
      delete process.env.SERVICES_FILE;
      delete process.env.DATA_DIR;
      process.env.SKIP_DATA_DIR_GUARD = '';   // ensure guard active
      const paths = loadPaths();
      // Force /etc/dashcaddy via env vars to simulate the regression path
      process.env.CADDY_BASE = '/etc/dashcaddy';
      const loaded = loadPaths();
      expect(() => loaded.assertSafe({ mode: 'production' })).toThrow(/forbidden image-layer/);
    });

    it('throws when dataDir resolves into /app/src', () => {
      process.env.SERVICES_FILE = '/app/src/security/foo.json';
      const paths = loadPaths();
      expect(() => paths.assertSafe({ mode: 'production' })).toThrow(/forbidden image-layer/);
    });

    it('throws when dataDir resolves into /app/routes', () => {
      process.env.SERVICES_FILE = '/app/routes/auth/services.json';
      const paths = loadPaths();
      expect(() => paths.assertSafe({ mode: 'production' })).toThrow(/forbidden image-layer/);
    });

    it('allows dataDir at /app/data (the standard production bind mount)', () => {
      process.env.SERVICES_FILE = '/app/data/services.json';
      const paths = loadPaths();
      expect(() => paths.assertSafe({ mode: 'production' })).not.toThrow();
    });

    it('allows dataDir at /opt/some-bind-mount', () => {
      process.env.SERVICES_FILE = '/opt/dashcaddy/dashcaddy-api/data/services.json';
      const paths = loadPaths();
      expect(() => paths.assertSafe({ mode: 'production' })).not.toThrow();
    });

    it('is a no-op when mode !== production (dev/test path)', () => {
      process.env.SERVICES_FILE = '/app/src/security/foo.json';  // would otherwise throw
      const paths = loadPaths();
      expect(() => paths.assertSafe({ mode: 'development' })).not.toThrow();
      expect(() => paths.assertSafe({ mode: 'test' })).not.toThrow();
      // Default mode is 'production' → a forbidden path MUST throw.
      expect(() => paths.assertSafe()).toThrow(/forbidden image-layer/);
    });

    it('is bypassed when SKIP_DATA_DIR_GUARD is set (escape hatch for legacy setups)', () => {
      process.env.SERVICES_FILE = '/app/src/security/foo.json';
      process.env.SKIP_DATA_DIR_GUARD = '1';
      const paths = loadPaths();
      expect(paths.assertSafe).toBeDefined();
      // Loader short-circuits if SKIP_DATA_DIR_GUARD was active at module load;
      // verify via fresh require after re-setting it
      delete require.cache[require.resolve('../platform-paths')];
      const loaded = require('../platform-paths');
      expect(() => loaded.assertSafe({ mode: 'production' })).not.toThrow();
    });
  });

  describe('isMountedCheck', () => {
    it('returns false for non-existent paths', () => {
      const paths = loadPaths();
      expect(paths.isMountedCheck('/this/does/not/exist/at/all/abc123')).toBe(false);
    });

    it('returns true for /tmp (writable on every Linux system)', () => {
      const paths = loadPaths();
      expect(paths.isMountedCheck('/tmp')).toBe(true);
    });

    it('returns false for /app alone (image layer without /app/data sub-mount)', () => {
      const paths = loadPaths();
      // In a Docker container this would be /app/data being a separate fs.
      // In a plain Linux test env, /app likely doesn't exist anyway.
      // Either way, the predicate should not throw and should return a boolean.
      const result = paths.isMountedCheck('/app');
      expect(typeof result).toBe('boolean');
    });
  });

  describe('Windows-specific defaults', () => {
    if (process.platform === 'win32') {
      it('caddyBase defaults to C:/caddy', () => {
        const paths = loadPaths();
        expect(paths.caddyBase).toBe('C:/caddy');
      });

      it('dockerData defaults to E:/dockerdata (network share)', () => {
        const paths = loadPaths();
        expect(paths.dockerData).toBe('E:/dockerdata');
      });

      it('caddyAdminUrl defaults to host.docker.internal (Docker Desktop)', () => {
        const paths = loadPaths();
        expect(paths.caddyAdminUrl).toContain('host.docker.internal');
      });
    }
  });
});
