import { describe, it, expect, vi, beforeEach } from 'vitest';
import { checkLimit } from './usage.js';

vi.mock('../db.js', () => ({
  getPool: vi.fn(() => ({
    query: vi.fn().mockResolvedValue([[{ count: 50 }]]),
  })),
}));

describe('checkLimit', () => {
  it('always allows enterprise plan regardless of usage', async () => {
    const result = await checkLimit('cust-1', 'enterprise');
    expect(result).toEqual({ allowed: true, limit: -1, used: 0 });
  });

  it('allows when usage is under limit', async () => {
    const { getPool } = await import('../db.js');
    vi.mocked(getPool).mockReturnValue({ query: vi.fn().mockResolvedValue([[{ count: 50 }]]) } as any);
    const result = await checkLimit('cust-1', 'growth');
    expect(result.allowed).toBe(true);
    expect(result.used).toBe(50);
    expect(result.limit).toBe(10000);
  });

  it('blocks when usage equals limit', async () => {
    const { getPool } = await import('../db.js');
    vi.mocked(getPool).mockReturnValue({ query: vi.fn().mockResolvedValue([[{ count: 1000 }]]) } as any);
    const result = await checkLimit('cust-1', 'starter');
    expect(result.allowed).toBe(false);
    expect(result.used).toBe(1000);
  });

  it('blocks when usage exceeds limit', async () => {
    const { getPool } = await import('../db.js');
    vi.mocked(getPool).mockReturnValue({ query: vi.fn().mockResolvedValue([[{ count: 1001 }]]) } as any);
    const result = await checkLimit('cust-1', 'free');
    expect(result.allowed).toBe(false);
  });

  it('does not query DB for enterprise plan', async () => {
    const { getPool } = await import('../db.js');
    const querySpy = vi.fn();
    vi.mocked(getPool).mockReturnValue({ query: querySpy } as any);
    await checkLimit('cust-1', 'enterprise');
    expect(querySpy).not.toHaveBeenCalled();
  });
});
