import { PlannerMetricsRepository } from './planner-metrics-repo';

describe('PlannerMetricsRepository', () => {
  function makeRepoWithRejectedQuery(error: Error & { code?: string }): PlannerMetricsRepository {
    const repo = new PlannerMetricsRepository();
    (repo as any).pool = {
      query: jest.fn().mockRejectedValue(error),
    };
    return repo;
  }

  it('treats transient connection errors as cache misses', async () => {
    const repo = makeRepoWithRejectedQuery(
      Object.assign(new Error('connect ECONNREFUSED 172.18.0.3:5432'), { code: 'ECONNREFUSED' })
    );

    await expect(repo.getCachedPlan('request-hash')).resolves.toBeNull();
  });

  it('skips cache writes when the planner metrics database is temporarily unreachable', async () => {
    const repo = makeRepoWithRejectedQuery(
      Object.assign(new Error('connect EHOSTUNREACH 76.53.10.36:443'), { code: 'EHOSTUNREACH' })
    );

    await expect(
      repo.cachePlan('request-hash', {
        planId: 'plan-1',
        generatedAt: new Date().toISOString(),
        decision: 'direct-pool',
        sourceChainId: 138,
        destinationChainId: 138,
        tokenIn: '0x1',
        tokenOut: '0x2',
        estimatedAmountOut: '1000',
        minAmountOut: '990',
        estimatedGasUsd: 0.1,
        legs: [],
        alternatives: [],
        confidenceScore: 0.9,
        riskFlags: [],
        selectedRouteReason: 'selected',
        rejectedAlternatives: [],
        staleness: { maxFreshnessSeconds: 0, hasStaleLeg: false },
      })
    ).resolves.toBeUndefined();
  });
});
