/**
 * Razorpay caps the `receipt` field at 40 characters. The old code built
 * receipts like `fee_<24-char ObjectId>_<13-digit timestamp>` = 42+ chars,
 * which Razorpay rejected ("receipt: the length must be no more than 40"),
 * surfacing as a failed order. This helper guarantees a unique receipt that
 * always fits, regardless of prefix or id length. Full ids live in `notes`.
 */
import { buildRazorpayReceipt } from './razorpay-receipt.helper';

describe('buildRazorpayReceipt', () => {
    const RZP_MAX = 40;

    it('never exceeds 40 chars for a typical fee receipt', () => {
        const r = buildRazorpayReceipt('fee', '6a0c1ccfd88c8defc9be3ac3'); // 24-char ObjectId
        expect(r.length).toBeLessThanOrEqual(RZP_MAX);
        expect(r.startsWith('fee_')).toBe(true);
    });

    it('never exceeds 40 chars for the payments two-id case', () => {
        // The worst offender: prod + product id + student id previously ~71 chars
        const r = buildRazorpayReceipt('prod', '6a0c1ccfd88c8defc9be3ac3');
        expect(r.length).toBeLessThanOrEqual(RZP_MAX);
    });

    it('fits even with a long prefix', () => {
        const r = buildRazorpayReceipt('transport', '6a0c1ccfd88c8defc9be3ac3');
        expect(r.length).toBeLessThanOrEqual(RZP_MAX);
        expect(r.startsWith('transport_')).toBe(true);
    });

    it('fits even with no id', () => {
        const r = buildRazorpayReceipt('inv');
        expect(r.length).toBeLessThanOrEqual(RZP_MAX);
    });

    it('fits even with an absurdly long prefix (defensive)', () => {
        const r = buildRazorpayReceipt('x'.repeat(100), '6a0c1ccfd88c8defc9be3ac3');
        expect(r.length).toBeLessThanOrEqual(RZP_MAX);
    });

    it('is reasonably unique across rapid calls', () => {
        const seen = new Set<string>();
        for (let i = 0; i < 500; i++) seen.add(buildRazorpayReceipt('fee', '6a0c1ccfd88c8defc9be3ac3'));
        // Allow a tiny collision margin but expect near-total uniqueness
        expect(seen.size).toBeGreaterThan(495);
    });

    it('includes a recognizable tail of the id for traceability', () => {
        const id = '6a0c1ccfd88c8defc9be3ac3';
        const r = buildRazorpayReceipt('fee', id);
        // last 6 of the id should appear, aiding dashboard lookup
        expect(r).toContain(id.slice(-6));
    });

    it('contains only receipt-safe characters', () => {
        const r = buildRazorpayReceipt('fee', '6a0c1ccfd88c8defc9be3ac3');
        expect(/^[A-Za-z0-9_]+$/.test(r)).toBe(true);
    });
});
