/**
 * Exhaustive integration spec — proves the admin "toggle active" flag
 * actually affects the student panel. Captures the exact MongoDB query
 * shape on every student-scoped read/write so a future regression that
 * silently drops the isActive filter will fail here.
 */
import { Test } from '@nestjs/testing';
import { getModelToken } from '@nestjs/mongoose';
import { NotFoundException } from '@nestjs/common';
import { InvoicesService } from './invoices.service';
import { Invoice } from './schemas/invoice.schema';
import { Student } from '../students/schemas/student.schema';
import { Class } from '../classes/schemas/class.schema';
import { SettingsService } from '../settings/settings.service';

jest.mock('razorpay', () => jest.fn().mockImplementation(() => ({
    orders: {
        create: jest.fn().mockResolvedValue({
            id: 'order_NEW',
            amount: 50000,
            currency: 'INR',
        }),
    },
})));

// Service reads Razorpay creds directly from process.env at construction time.
beforeAll(() => {
    process.env.RAZORPAY_KEY_ID = 'rzp_test_KEY';
    process.env.RAZORPAY_KEY_SECRET = 'secret_test';
});

function stub(overrides: any = {}) {
    return {
        find: jest.fn(),
        findOne: jest.fn(),
        findById: jest.fn(),
        findByIdAndUpdate: jest.fn(),
        findOneAndUpdate: jest.fn(),
        exists: jest.fn(),
        create: jest.fn(),
        countDocuments: jest.fn(),
        ...overrides,
    };
}

async function makeService(invoiceModelStub: any): Promise<InvoicesService> {
    const mod = await Test.createTestingModule({
        providers: [
            InvoicesService,
            { provide: getModelToken(Invoice.name), useValue: invoiceModelStub },
            { provide: getModelToken(Student.name), useValue: stub() },
            { provide: getModelToken(Class.name), useValue: stub() },
            {
                provide: SettingsService,
                useValue: {
                    getRazorpayCreds: jest.fn().mockResolvedValue({
                        keyId: 'rzp_test_KEY',
                        keySecret: 'secret_test',
                    }),
                },
            },
        ],
    }).compile();
    return mod.get(InvoicesService);
}

describe('Admin toggle-active → student visibility (query-shape assertions)', () => {
    describe('findOneForStudent', () => {
        it('queries with { _id, studentId, isActive: true } — exact shape', async () => {
            const findOne = jest.fn().mockReturnValue({
                lean: () => Promise.resolve({ _id: 'inv1', studentId: 'stu1', isActive: true }),
            });
            const svc = await makeService(stub({ findOne }));
            await svc.findOneForStudent('inv1', 'stu1');
            expect(findOne).toHaveBeenCalledTimes(1);
            const queryArg = findOne.mock.calls[0][0];
            expect(queryArg).toEqual({ _id: 'inv1', studentId: 'stu1', isActive: true });
            // Defensive: explicitly verify the isActive clause is *present*
            // (otherwise an admin-deactivated invoice would still be returned).
            expect(queryArg).toHaveProperty('isActive', true);
        });

        it('throws 404 when admin has deactivated the invoice (findOne returns null)', async () => {
            const findOne = jest.fn().mockReturnValue({ lean: () => Promise.resolve(null) });
            const svc = await makeService(stub({ findOne }));
            await expect(svc.findOneForStudent('inv1', 'stu1'))
                .rejects.toThrow(NotFoundException);
        });
    });

    describe('createRazorpayOrder', () => {
        it('queries with { _id, studentId, isActive: true } — admin-disabled invoices blocked at pay-init', async () => {
            const findOne = jest.fn().mockReturnValue({
                lean: () => Promise.resolve({
                    _id: 'inv1', studentId: 'stu1', isActive: true,
                    amount: 500, totalPaid: 0, status: 'pending',
                    allowPartialPayment: true,
                }),
            });
            const findByIdAndUpdate = jest.fn().mockResolvedValue(null);
            const svc = await makeService(stub({ findOne, findByIdAndUpdate }));
            await svc.createRazorpayOrder('inv1', 'stu1');
            expect(findOne.mock.calls[0][0]).toEqual({
                _id: 'inv1', studentId: 'stu1', isActive: true,
            });
            expect(findOne.mock.calls[0][0]).toHaveProperty('isActive', true);
        });

        it('throws 404 when admin has deactivated the invoice (cannot create order)', async () => {
            const findOne = jest.fn().mockReturnValue({ lean: () => Promise.resolve(null) });
            const svc = await makeService(stub({ findOne }));
            await expect(svc.createRazorpayOrder('inv1', 'stu1'))
                .rejects.toThrow(NotFoundException);
        });
    });

    describe('verifyRazorpayPayment — intentional design: no isActive filter', () => {
        // Razorpay has already collected money at this point. Filtering by
        // isActive here would silently drop the payment, double-charging the
        // student or losing reconciliation. Verifying acceptance.
        it('accepts payment EVEN IF admin disabled the invoice mid-flight', async () => {
            const crypto = require('crypto');
            const expected = crypto
                .createHmac('sha256', 'secret_test')
                .update('order_NEW|pay_X')
                .digest('hex');

            const findOne = jest.fn().mockReturnValue({
                lean: () => Promise.resolve({
                    _id: 'inv1', studentId: 'stu1',
                    isActive: false,         // ← admin disabled it
                    amount: 500, totalPaid: 0, status: 'pending',
                    allowPartialPayment: true,
                    razorpayOrderId: 'order_NEW',
                    razorpayOrderAmount: 500,
                }),
            });
            const findOneAndUpdate = jest.fn().mockReturnValue({
                lean: () => Promise.resolve({
                    _id: 'inv1', totalPaid: 500, status: 'paid',
                }),
            });
            // generatePaymentId/generateReceiptNumber call countDocuments + exists
            // in a 3-attempt loop. Mock both so the helpers return clean ids.
            const svc = await makeService(stub({
                findOne,
                findOneAndUpdate,
                countDocuments: jest.fn().mockResolvedValue(0),
                exists: jest.fn().mockResolvedValue(false),
            }));

            await svc.verifyRazorpayPayment('inv1', 'stu1', {
                razorpay_order_id: 'order_NEW',
                razorpay_payment_id: 'pay_X',
                razorpay_signature: expected,
            });

            // Critical assertion: the query for the invoice (to verify) does
            // NOT include isActive — only ownership + order match. Money was
            // already collected; can't refuse to record it.
            const queryArg = findOne.mock.calls[0][0];
            expect(queryArg).not.toHaveProperty('isActive');
            expect(queryArg).toEqual({
                _id: 'inv1',
                studentId: 'stu1',
                razorpayOrderId: 'order_NEW',
            });
        });
    });

    describe('findAll — list path query construction', () => {
        // The admin controller injects filter.isActive=true for STUDENT role
        // BEFORE calling findAll. Then service.buildQuery propagates that into
        // the actual Mongo query. Verifying the propagation here.
        it('respects an explicit filter.isActive=true (student-list path)', async () => {
            const findCallback = jest.fn();
            const find = jest.fn().mockImplementation((q: any) => {
                findCallback(q);
                return {
                    sort: () => ({
                        limit: () => ({
                            lean: () => Promise.resolve([]),
                        }),
                    }),
                };
            });
            const svc = await makeService(stub({ find, countDocuments: jest.fn().mockResolvedValue(0) }));
            await svc.findAll({ studentId: 'stu1', isActive: true } as any);
            expect(findCallback).toHaveBeenCalled();
            const queryArg = findCallback.mock.calls[0][0];
            expect(queryArg).toMatchObject({ studentId: 'stu1', isActive: true });
        });

        it('omits isActive when filter.isActive is undefined (admin-list default)', async () => {
            const findCallback = jest.fn();
            const find = jest.fn().mockImplementation((q: any) => {
                findCallback(q);
                return {
                    sort: () => ({
                        limit: () => ({
                            lean: () => Promise.resolve([]),
                        }),
                    }),
                };
            });
            const svc = await makeService(stub({ find, countDocuments: jest.fn().mockResolvedValue(0) }));
            await svc.findAll({} as any);
            const queryArg = findCallback.mock.calls[0][0];
            expect(queryArg).not.toHaveProperty('isActive');
        });

        it('respects an explicit filter.isActive=false (would allow admin to view disabled)', async () => {
            const findCallback = jest.fn();
            const find = jest.fn().mockImplementation((q: any) => {
                findCallback(q);
                return {
                    sort: () => ({
                        limit: () => ({
                            lean: () => Promise.resolve([]),
                        }),
                    }),
                };
            });
            const svc = await makeService(stub({ find, countDocuments: jest.fn().mockResolvedValue(0) }));
            await svc.findAll({ isActive: false } as any);
            const queryArg = findCallback.mock.calls[0][0];
            expect(queryArg).toMatchObject({ isActive: false });
        });
    });

    describe('toggleActive — atomic pipeline', () => {
        it('uses Mongo aggregation pipeline to flip isActive atomically', async () => {
            const findByIdAndUpdate = jest.fn().mockReturnValue({
                lean: () => Promise.resolve({ _id: 'inv1', isActive: false }),
            });
            const svc = await makeService(stub({ findByIdAndUpdate }));
            const result = await svc.toggleActive('inv1');
            expect(findByIdAndUpdate).toHaveBeenCalledWith(
                'inv1',
                [{ $set: { isActive: { $not: '$isActive' } } }],
                { new: true, projection: { isActive: 1 } },
            );
            expect(result).toEqual({ _id: 'inv1', isActive: false });
        });

        it('throws 404 if invoice does not exist', async () => {
            const findByIdAndUpdate = jest.fn().mockReturnValue({
                lean: () => Promise.resolve(null),
            });
            const svc = await makeService(stub({ findByIdAndUpdate }));
            await expect(svc.toggleActive('missing')).rejects.toThrow(NotFoundException);
        });
    });
});
