import { BadRequestException } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { getModelToken } from '@nestjs/mongoose';
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';

// Shared SettingsService stub — returns test Razorpay creds so payment paths run.
const stubSettingsProvider = {
    provide: SettingsService,
    useValue: {
        getRazorpayCreds: jest.fn().mockResolvedValue({
            keyId: 'rzp_test_KEY',
            keySecret: 'secret_test',
        }),
    },
};

function stubModel(overrides: any = {}): any {
    const chain = (result: any) => ({ lean: () => Promise.resolve(result) });
    return {
        find: jest.fn().mockReturnValue({ ...chain([]), sort: () => chain([]), limit: () => chain([]) }),
        findOne: jest.fn().mockReturnValue(chain(null)),
        findById: jest.fn().mockReturnValue(chain(null)),
        create: jest.fn(),
        findByIdAndUpdate: jest.fn().mockReturnValue(chain(null)),
        findOneAndUpdate: jest.fn().mockReturnValue(chain(null)),
        countDocuments: jest.fn().mockResolvedValue(0),
        exists: jest.fn().mockResolvedValue(false),
        ...overrides,
    };
}

async function makeService(): Promise<InvoicesService> {
    const mod: TestingModule = await Test.createTestingModule({
        providers: [
            InvoicesService,
            { provide: getModelToken(Invoice.name), useValue: stubModel() },
            { provide: getModelToken(Student.name), useValue: stubModel() },
            { provide: getModelToken(Class.name), useValue: stubModel() },
            stubSettingsProvider,
        ],
    }).compile();
    return mod.get(InvoicesService);
}

describe('InvoicesService.validatePartialRule', () => {
    let service: InvoicesService;

    beforeEach(async () => {
        service = await makeService();
    });

    // The helper is private — exercise via cast.
    const call = (allow: boolean | undefined, amount: number, totalPaid: number) =>
        (service as any).validatePartialRule(allow, amount, totalPaid);

    it('accepts totalPaid=0 when partial not allowed', () => {
        expect(() => call(false, 1000, 0)).not.toThrow();
    });

    it('accepts totalPaid=amount when partial not allowed', () => {
        expect(() => call(false, 1000, 1000)).not.toThrow();
    });

    it('rejects partial value when partial not allowed', () => {
        expect(() => call(false, 1000, 500)).toThrow(BadRequestException);
        expect(() => call(false, 1000, 1)).toThrow(BadRequestException);
        expect(() => call(false, 1000, 999)).toThrow(BadRequestException);
    });

    it('accepts any value when partial allowed', () => {
        expect(() => call(true, 1000, 0)).not.toThrow();
        expect(() => call(true, 1000, 500)).not.toThrow();
        expect(() => call(true, 1000, 1000)).not.toThrow();
    });

    it('accepts any value when allowPartial is undefined (legacy / fee-linked)', () => {
        expect(() => call(undefined, 1000, 0)).not.toThrow();
        expect(() => call(undefined, 1000, 500)).not.toThrow();
        expect(() => call(undefined, 1000, 1000)).not.toThrow();
    });
});

describe('InvoicesService.create — partial-payment policy', () => {
    let service: InvoicesService;
    let invoiceModel: any;
    let studentModel: any;
    let classModel: any;

    beforeEach(async () => {
        const studentDoc = { _id: 'stu1', name: 'Test Student', uniqueId: 'STU-1', classId: 'c1' };
        const classDoc = { _id: 'c1', name: 'Class 1' };

        studentModel = stubModel({
            findById: jest.fn().mockReturnValue({ lean: () => Promise.resolve(studentDoc) }),
        });
        classModel = stubModel({
            findById: jest.fn().mockReturnValue({ lean: () => Promise.resolve(classDoc) }),
        });
        invoiceModel = stubModel({
            create: jest.fn().mockImplementation(async (doc: any) => ({
                ...doc,
                _id: 'inv1',
                toObject: () => ({ ...doc, _id: 'inv1' }),
            })),
        });

        const mod: TestingModule = await Test.createTestingModule({
            providers: [
                InvoicesService,
                { provide: getModelToken(Invoice.name), useValue: invoiceModel },
                { provide: getModelToken(Student.name), useValue: studentModel },
                { provide: getModelToken(Class.name), useValue: classModel },
                stubSettingsProvider,
            ],
        }).compile();
        service = mod.get(InvoicesService);
    });

    it('persists allowPartialPayment=true on create', async () => {
        await service.create({
            studentId: 'stu1',
            amount: 1000,
            totalPaid: 0,
            allowPartialPayment: true,
        } as any, 'ay1');
        const created = invoiceModel.create.mock.calls[0][0];
        expect(created.allowPartialPayment).toBe(true);
    });

    it('persists allowPartialPayment=false on create', async () => {
        await service.create({
            studentId: 'stu1',
            amount: 1000,
            totalPaid: 0,
            allowPartialPayment: false,
        } as any, 'ay1');
        const created = invoiceModel.create.mock.calls[0][0];
        expect(created.allowPartialPayment).toBe(false);
    });

    it('rejects create with allowPartialPayment=false and partial totalPaid', async () => {
        await expect(service.create({
            studentId: 'stu1',
            amount: 1000,
            totalPaid: 500,
            allowPartialPayment: false,
        } as any, 'ay1')).rejects.toThrow(BadRequestException);
    });

    it('accepts create with allowPartialPayment=false and totalPaid=amount (paid in full)', async () => {
        await expect(service.create({
            studentId: 'stu1',
            amount: 1000,
            totalPaid: 1000,
            allowPartialPayment: false,
        } as any, 'ay1')).resolves.toBeDefined();
    });
});

describe('InvoicesService.update — partial-payment policy', () => {
    async function makeUpdateService(existing: any) {
        const invoiceModel = stubModel({
            findById: jest.fn().mockReturnValue({ lean: () => Promise.resolve(existing) }),
            findOneAndUpdate: jest.fn().mockReturnValue({
                lean: () => Promise.resolve({ ...existing, _id: existing._id }),
            }),
        });
        const mod = await Test.createTestingModule({
            providers: [
                InvoicesService,
                { provide: getModelToken(Invoice.name), useValue: invoiceModel },
                { provide: getModelToken(Student.name), useValue: stubModel() },
                { provide: getModelToken(Class.name), useValue: stubModel() },
            stubSettingsProvider,
            ],
        }).compile();
        return mod.get(InvoicesService);
    }

    it('rejects update with totalPaid=partial when existing.allowPartialPayment=false', async () => {
        const service = await makeUpdateService({
            _id: 'inv1', amount: 1000, totalPaid: 0, status: 'pending',
            allowPartialPayment: false,
        });
        await expect(service.update('inv1', { totalPaid: 500 } as any))
            .rejects.toThrow(BadRequestException);
    });

    it('accepts update with totalPaid=amount (full) when existing.allowPartialPayment=false', async () => {
        const service = await makeUpdateService({
            _id: 'inv1', amount: 1000, totalPaid: 0, status: 'pending',
            allowPartialPayment: false,
        });
        await expect(service.update('inv1', { totalPaid: 1000 } as any))
            .resolves.toBeDefined();
    });

    it('accepts partial update when existing.allowPartialPayment=true', async () => {
        const service = await makeUpdateService({
            _id: 'inv1', amount: 1000, totalPaid: 0, status: 'pending',
            allowPartialPayment: true,
        });
        await expect(service.update('inv1', { totalPaid: 500 } as any))
            .resolves.toBeDefined();
    });

    it('accepts partial update when existing.allowPartialPayment is undefined (legacy)', async () => {
        const service = await makeUpdateService({
            _id: 'inv1', amount: 1000, totalPaid: 0, status: 'pending',
        });
        await expect(service.update('inv1', { totalPaid: 500 } as any))
            .resolves.toBeDefined();
    });
});

describe('InvoicesService.upsertFromFeePayment — partial-payment policy', () => {
    let service: InvoicesService;
    let invoiceModel: any;

    beforeEach(async () => {
        invoiceModel = stubModel({
            findOne: jest.fn().mockReturnValue({ lean: () => Promise.resolve(null) }),
            create: jest.fn().mockImplementation(async (doc: any) => ({
                ...doc, _id: 'inv1', toObject: () => ({ ...doc, _id: 'inv1' }),
            })),
        });
        const studentModel = stubModel({
            findById: jest.fn().mockReturnValue({ lean: () => Promise.resolve({ _id: 'stu1', name: 'X', uniqueId: 'X' }) }),
        });
        const classModel = stubModel({
            findById: jest.fn().mockReturnValue({ lean: () => Promise.resolve({ _id: 'c1', name: 'Class 1' }) }),
        });

        const mod: TestingModule = await Test.createTestingModule({
            providers: [
                InvoicesService,
                { provide: getModelToken(Invoice.name), useValue: invoiceModel },
                { provide: getModelToken(Student.name), useValue: studentModel },
                { provide: getModelToken(Class.name), useValue: classModel },
                stubSettingsProvider,
            ],
        }).compile();
        service = mod.get(InvoicesService);
    });

    it('does NOT write allowPartialPayment when creating from a fee payment', async () => {
        await service.upsertFromFeePayment({
            feeAssignmentId: 'fa1',
            studentId: 'stu1',
            classId: 'c1',
            academicYearId: 'ay1',
            billAmount: 1000,
            totalPaid: 500,
            paymentMethod: 'razorpay',
            generatedBy: 'System',
        });
        const created = invoiceModel.create.mock.calls[0][0];
        expect(created.allowPartialPayment).toBeUndefined();
    });
});

describe('InvoicesService.findOneForStudent', () => {
    let service: InvoicesService;
    let invoiceModel: any;

    function makeService(invoiceDoc: any) {
        invoiceModel = stubModel({
            findOne: jest.fn().mockReturnValue({ lean: () => Promise.resolve(invoiceDoc) }),
        });
        return Test.createTestingModule({
            providers: [
                InvoicesService,
                { provide: getModelToken(Invoice.name), useValue: invoiceModel },
                { provide: getModelToken(Student.name), useValue: stubModel() },
                { provide: getModelToken(Class.name), useValue: stubModel() },
            stubSettingsProvider,
            ],
        }).compile().then((mod) => mod.get(InvoicesService));
    }

    it('returns the invoice when matched', async () => {
        service = await makeService({ _id: 'inv1', studentId: 'stu1', isActive: true, amount: 1000 });
        const out = await service.findOneForStudent('inv1', 'stu1');
        expect((out as any)._id).toBe('inv1');
    });

    it('throws NotFoundException when invoice is missing / not the student\'s', async () => {
        const { NotFoundException } = require('@nestjs/common');
        service = await makeService(null);
        await expect(service.findOneForStudent('inv1', 'stu1')).rejects.toThrow(NotFoundException);
    });

    it('throws NotFoundException for isActive=false (filtered)', async () => {
        const { NotFoundException } = require('@nestjs/common');
        service = await makeService(null);
        await expect(service.findOneForStudent('inv1', 'stu1')).rejects.toThrow(NotFoundException);
    });
});

// Mock Razorpay SDK at the top level — must be done BEFORE any test that
// constructs an InvoicesService that may try to talk to Razorpay.
// Shared orders.create mock so tests can inspect the exact payload (e.g. the
// receipt string) passed to Razorpay.
const ordersCreateMock = jest.fn().mockResolvedValue({
    id: 'order_TEST_123',
    amount: 100000,  // paise
    currency: 'INR',
});
jest.mock('razorpay', () => {
    return jest.fn().mockImplementation(() => ({
        orders: { create: (...args: any[]) => ordersCreateMock(...args) },
    }));
});

describe('InvoicesService.createRazorpayOrder', () => {
    let service: InvoicesService;
    let invoiceModel: any;

    async function setupService(existing: any) {
        invoiceModel = stubModel({
            findOne: jest.fn().mockReturnValue({ lean: () => Promise.resolve(existing) }),
            findByIdAndUpdate: jest.fn().mockResolvedValue(null),
        });
        const mod = await Test.createTestingModule({
            providers: [
                InvoicesService,
                { provide: getModelToken(Invoice.name), useValue: invoiceModel },
                { provide: getModelToken(Student.name), useValue: stubModel() },
                { provide: getModelToken(Class.name), useValue: stubModel() },
            stubSettingsProvider,
            ],
        }).compile();
        const s = mod.get(InvoicesService);
        (s as any).razorpayKeyId = 'key_test';
        (s as any).razorpayKeySecret = 'secret_test';
        (s as any).razor = new (require('razorpay'))();
        return s;
    }

    it('uses balance when amount omitted', async () => {
        service = await setupService({
            _id: 'inv1', studentId: 'stu1', isActive: true,
            amount: 1000, totalPaid: 300, status: 'partial',
            allowPartialPayment: true,
        });
        const r = await service.createRazorpayOrder('inv1', 'stu1');
        expect(r.orderId).toBe('order_TEST_123');
        expect(invoiceModel.findByIdAndUpdate).toHaveBeenCalledWith(
            'inv1',
            expect.objectContaining({ $set: expect.objectContaining({ razorpayOrderAmount: 700 }) }),
        );
    });

    it('passes Razorpay a receipt that satisfies the 40-char limit (the reported bug)', async () => {
        ordersCreateMock.mockClear();
        // A real 24-char Mongo ObjectId — the old `inv_<id>_<ts>` format was 42 chars.
        const longId = '6a0c1ccfd88c8defc9be3ac3';
        service = await setupService({
            _id: longId, studentId: 'stu1', isActive: true,
            amount: 1000, totalPaid: 0, status: 'pending',
            allowPartialPayment: true,
        });
        await service.createRazorpayOrder(longId, 'stu1');
        expect(ordersCreateMock).toHaveBeenCalledTimes(1);
        const payload = ordersCreateMock.mock.calls[0][0];
        expect(typeof payload.receipt).toBe('string');
        expect(payload.receipt.length).toBeLessThanOrEqual(40);
        // Full id still travels in notes for traceability
        expect(payload.notes).toMatchObject({ invoiceId: longId, studentId: 'stu1' });
    });

    it('rejects amount > balance', async () => {
        service = await setupService({
            _id: 'inv1', studentId: 'stu1', isActive: true,
            amount: 1000, totalPaid: 300, status: 'partial',
            allowPartialPayment: true,
        });
        await expect(service.createRazorpayOrder('inv1', 'stu1', 800))
            .rejects.toThrow(BadRequestException);
    });

    it('rejects partial when policy=false', async () => {
        service = await setupService({
            _id: 'inv1', studentId: 'stu1', isActive: true,
            amount: 1000, totalPaid: 0, status: 'pending',
            allowPartialPayment: false,
        });
        await expect(service.createRazorpayOrder('inv1', 'stu1', 500))
            .rejects.toThrow(BadRequestException);
    });

    it('accepts full balance when policy=false', async () => {
        service = await setupService({
            _id: 'inv1', studentId: 'stu1', isActive: true,
            amount: 1000, totalPaid: 0, status: 'pending',
            allowPartialPayment: false,
        });
        await expect(service.createRazorpayOrder('inv1', 'stu1', 1000))
            .resolves.toBeDefined();
    });

    it('reuses existing order on amount-match (within Rs 0.01)', async () => {
        service = await setupService({
            _id: 'inv1', studentId: 'stu1', isActive: true,
            amount: 1000, totalPaid: 0, status: 'pending',
            allowPartialPayment: true,
            razorpayOrderId: 'order_OLD_456', razorpayOrderAmount: 500,
        });
        const r = await service.createRazorpayOrder('inv1', 'stu1', 500);
        expect(r.orderId).toBe('order_OLD_456');
        expect(invoiceModel.findByIdAndUpdate).not.toHaveBeenCalled();
    });

    it('creates new order when amount differs', async () => {
        service = await setupService({
            _id: 'inv1', studentId: 'stu1', isActive: true,
            amount: 1000, totalPaid: 0, status: 'pending',
            allowPartialPayment: true,
            razorpayOrderId: 'order_OLD_456', razorpayOrderAmount: 500,
        });
        const r = await service.createRazorpayOrder('inv1', 'stu1', 700);
        expect(r.orderId).toBe('order_TEST_123');
        expect(invoiceModel.findByIdAndUpdate).toHaveBeenCalled();
    });

    it('throws NotFoundException for missing/wrong-student/inactive invoice', async () => {
        const { NotFoundException } = require('@nestjs/common');
        service = await setupService(null);
        await expect(service.createRazorpayOrder('inv1', 'stu1'))
            .rejects.toThrow(NotFoundException);
    });

    it('rejects already-paid invoice', async () => {
        service = await setupService({
            _id: 'inv1', studentId: 'stu1', isActive: true,
            amount: 1000, totalPaid: 1000, status: 'paid',
        });
        await expect(service.createRazorpayOrder('inv1', 'stu1'))
            .rejects.toThrow(BadRequestException);
    });
});

describe('InvoicesService.verifyRazorpayPayment', () => {
    let service: InvoicesService;
    let invoiceModel: any;
    const SECRET = 'secret_test';
    const ORDER_ID = 'order_TEST_123';
    const PAYMENT_ID = 'pay_TEST_999';

    function makeSig(orderId: string, paymentId: string, secret: string = SECRET): string {
        return require('crypto')
            .createHmac('sha256', secret)
            .update(`${orderId}|${paymentId}`)
            .digest('hex');
    }

    async function setupService(existing: any, updated: any = existing) {
        invoiceModel = stubModel({
            findOne: jest.fn().mockReturnValue({ lean: () => Promise.resolve(existing) }),
            findOneAndUpdate: jest.fn().mockReturnValue({
                lean: () => Promise.resolve(updated && { ...updated, _id: existing?._id || 'inv1' }),
            }),
            countDocuments: jest.fn().mockResolvedValue(0),
            exists: jest.fn().mockResolvedValue(false),
        });
        const mod = await Test.createTestingModule({
            providers: [
                InvoicesService,
                { provide: getModelToken(Invoice.name), useValue: invoiceModel },
                { provide: getModelToken(Student.name), useValue: stubModel() },
                { provide: getModelToken(Class.name), useValue: stubModel() },
            stubSettingsProvider,
            ],
        }).compile();
        const s = mod.get(InvoicesService);
        (s as any).razorpayKeySecret = SECRET;
        return s;
    }

    it('rejects bad signature', async () => {
        service = await setupService({ _id: 'inv1' });
        await expect(service.verifyRazorpayPayment('inv1', 'stu1', {
            razorpay_order_id: ORDER_ID,
            razorpay_payment_id: PAYMENT_ID,
            razorpay_signature: 'wrong_signature',
        })).rejects.toThrow(BadRequestException);
    });

    it('throws NotFoundException for mismatched order_id (stale or replay)', async () => {
        const { NotFoundException } = require('@nestjs/common');
        service = await setupService(null);
        await expect(service.verifyRazorpayPayment('inv1', 'stu1', {
            razorpay_order_id: ORDER_ID,
            razorpay_payment_id: PAYMENT_ID,
            razorpay_signature: makeSig(ORDER_ID, PAYMENT_ID),
        })).rejects.toThrow(NotFoundException);
    });

    it('updates totalPaid + sets paymentMode=online + clears razorpayOrderId', async () => {
        const before = {
            _id: 'inv1', studentId: 'stu1', amount: 1000, totalPaid: 0,
            status: 'pending', allowPartialPayment: true,
            razorpayOrderId: ORDER_ID, razorpayOrderAmount: 500,
        };
        service = await setupService(before, { ...before, totalPaid: 500, status: 'partial' });
        const r = await service.verifyRazorpayPayment('inv1', 'stu1', {
            razorpay_order_id: ORDER_ID,
            razorpay_payment_id: PAYMENT_ID,
            razorpay_signature: makeSig(ORDER_ID, PAYMENT_ID),
        });
        expect(r).toBeDefined();
        const updateCall = invoiceModel.findOneAndUpdate.mock.calls[0];
        expect(updateCall[1].$set.totalPaid).toBe(500);
        expect(updateCall[1].$set.paymentMode).toBe('online');
        expect(updateCall[1].$set.razorpayPaymentId).toBe(PAYMENT_ID);
        expect(updateCall[1].$unset).toEqual(expect.objectContaining({
            razorpayOrderId: 1, razorpayOrderAmount: 1,
        }));
    });

    it('generates paymentId + receiptNumber + transactionId at first paid-transition', async () => {
        const before = {
            _id: 'inv1', studentId: 'stu1', amount: 1000, totalPaid: 0,
            status: 'pending', allowPartialPayment: true,
            razorpayOrderId: ORDER_ID, razorpayOrderAmount: 1000,
        };
        service = await setupService(before, { ...before, totalPaid: 1000, status: 'paid' });
        await service.verifyRazorpayPayment('inv1', 'stu1', {
            razorpay_order_id: ORDER_ID,
            razorpay_payment_id: PAYMENT_ID,
            razorpay_signature: makeSig(ORDER_ID, PAYMENT_ID),
        });
        const set = invoiceModel.findOneAndUpdate.mock.calls[0][1].$set;
        expect(set.paymentId).toMatch(/^PAY-/);
        expect(set.receiptNumber).toMatch(/^RCPT-/);
        expect(set.transactionId).toBe(PAYMENT_ID);  // razorpay_payment_id beats auto-gen TXN
    });

    it('does NOT regenerate paymentId/receiptNumber on subsequent payment', async () => {
        const before = {
            _id: 'inv1', studentId: 'stu1', amount: 1000, totalPaid: 500,
            status: 'partial', allowPartialPayment: true,
            paymentId: 'PAY-2026-EXISTING', receiptNumber: 'RCPT-2026-EXISTING', transactionId: 'TXN-EXISTING',
            razorpayOrderId: ORDER_ID, razorpayOrderAmount: 500,
        };
        service = await setupService(before, { ...before, totalPaid: 1000, status: 'paid' });
        await service.verifyRazorpayPayment('inv1', 'stu1', {
            razorpay_order_id: ORDER_ID,
            razorpay_payment_id: PAYMENT_ID,
            razorpay_signature: makeSig(ORDER_ID, PAYMENT_ID),
        });
        const set = invoiceModel.findOneAndUpdate.mock.calls[0][1].$set;
        expect(set.paymentId).toBeUndefined();
        expect(set.receiptNumber).toBeUndefined();
        expect(set.transactionId).toBeUndefined();
    });

    it('rejects overpay (defensive)', async () => {
        const before = {
            _id: 'inv1', studentId: 'stu1', amount: 1000, totalPaid: 800,
            status: 'partial', allowPartialPayment: true,
            razorpayOrderId: ORDER_ID, razorpayOrderAmount: 500,  // would push to 1300
        };
        service = await setupService(before);
        await expect(service.verifyRazorpayPayment('inv1', 'stu1', {
            razorpay_order_id: ORDER_ID,
            razorpay_payment_id: PAYMENT_ID,
            razorpay_signature: makeSig(ORDER_ID, PAYMENT_ID),
        })).rejects.toThrow(BadRequestException);
    });

    it('honors validatePartialRule (Require-Full + would-be-partial total)', async () => {
        const before = {
            _id: 'inv1', studentId: 'stu1', amount: 1000, totalPaid: 0,
            status: 'pending', allowPartialPayment: false,
            razorpayOrderId: ORDER_ID, razorpayOrderAmount: 500,
        };
        service = await setupService(before);
        await expect(service.verifyRazorpayPayment('inv1', 'stu1', {
            razorpay_order_id: ORDER_ID,
            razorpay_payment_id: PAYMENT_ID,
            razorpay_signature: makeSig(ORDER_ID, PAYMENT_ID),
        })).rejects.toThrow(BadRequestException);
    });

    it('returns 400 "already processed" on concurrent verify', async () => {
        const before = {
            _id: 'inv1', studentId: 'stu1', amount: 1000, totalPaid: 0,
            status: 'pending', allowPartialPayment: true,
            razorpayOrderId: ORDER_ID, razorpayOrderAmount: 1000,
        };
        // findOneAndUpdate returns null → another request already won.
        service = await setupService(before, null);
        await expect(service.verifyRazorpayPayment('inv1', 'stu1', {
            razorpay_order_id: ORDER_ID,
            razorpay_payment_id: PAYMENT_ID,
            razorpay_signature: makeSig(ORDER_ID, PAYMENT_ID),
        })).rejects.toThrow(/already processed/);
    });
});
