import { IProxyProvider, AcquireOpts, ProxyInfo, HealthCheckResult } from './interface.js';

const HEALTH_URL = 'https://www.baidu.com';
const HEALTH_TIMEOUT = 5000;

export class LocalProxyProvider implements IProxyProvider {
  readonly name = 'local';

  async acquire(opts: AcquireOpts): Promise<ProxyInfo> {
    return {
      externalId: `local-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
      mode: 'local',
      protocol: 'http',
      region: opts.region,
      isp: opts.isp,
    };
  }

  async release(_externalId: string): Promise<void> {}

  async healthCheck(_p: ProxyInfo): Promise<HealthCheckResult> {
    const ctrl = new AbortController();
    const timer = setTimeout(() => ctrl.abort(), HEALTH_TIMEOUT);
    const start = Date.now();
    try {
      const res = await fetch(HEALTH_URL, { signal: ctrl.signal, method: 'HEAD' });
      return { ok: res.ok, latencyMs: Date.now() - start };
    } catch {
      return { ok: false, latencyMs: Date.now() - start };
    } finally {
      clearTimeout(timer);
    }
  }
}
