import * as crypto from 'crypto';
import { createHmac, timingSafeEqual } from 'crypto';
import Razorpay from 'razorpay';
import { Injectable, Logger, NotFoundException, BadRequestException, ServiceUnavailableException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Invoice, InvoiceDocument } from './schemas/invoice.schema';
import { Student } from '../students/schemas/student.schema';
import { Class } from '../classes/schemas/class.schema';
import { CreateInvoiceDto } from './dto/create-invoice.dto';
import { UpdateInvoiceDto } from './dto/update-invoice.dto';
import { FilterInvoicesDto } from './dto/filter-invoices.dto';
import { SettingsService } from '../settings/settings.service';
import { extractRazorpayErrorMessage, isRazorpayAuthError } from '../common/helpers/razorpay-error.helper';
import { buildRazorpayReceipt } from '../common/helpers/razorpay-receipt.helper';

@Injectable()
export class InvoicesService {
    private readonly logger = new Logger(InvoicesService.name);
    // Cached Razorpay state. `razorpayKeySecret` is needed by the HMAC verify
    // step; both are refreshed lazily on each payment-related call so admins
    // who update credentials via settings UI take effect immediately.
    private razor?: Razorpay;
    private razorpayKeyId: string = '';
    private razorpayKeySecret: string = '';

    constructor(
        @InjectModel(Invoice.name) private invoiceModel: Model<InvoiceDocument>,
        @InjectModel(Student.name) private studentModel: Model<any>,
        @InjectModel(Class.name) private classModel: Model<any>,
        private readonly settingsService: SettingsService,
    ) {}

    /**
     * Loads Razorpay credentials from settings (DB) with env-var fallback,
     * caching the SDK instance until the keys change. Called at the start of
     * every payment operation so admin updates take effect without restart.
     */
    private async refreshRazorpayCreds(): Promise<void> {
        const creds = await this.settingsService.getRazorpayCreds();
        if (creds.keyId !== this.razorpayKeyId || creds.keySecret !== this.razorpayKeySecret) {
            this.razorpayKeyId = creds.keyId;
            this.razorpayKeySecret = creds.keySecret;
            this.razor = creds.keyId && creds.keySecret
                ? new Razorpay({ key_id: creds.keyId, key_secret: creds.keySecret })
                : undefined;
        }
    }

    private getRazorpay(): Razorpay {
        if (!this.razor) {
            throw new BadRequestException('Online payments are not configured. Set Razorpay keys in Settings.');
        }
        return this.razor;
    }

    // =====================
    //  Helpers
    // =====================

    private deriveStatus(amount: number, totalPaid: number): 'paid' | 'partial' | 'pending' {
        if (totalPaid >= amount) return 'paid';
        if (totalPaid > 0) return 'partial';
        return 'pending';
    }

    /** Throws BadRequest when the invoice's policy disallows partial values.
     *  `undefined` is treated as "allowed" for backward compat with legacy
     *  rows and fee-linked invoices. */
    private validatePartialRule(
        allowPartial: boolean | undefined,
        amount: number,
        totalPaid: number,
    ): void {
        if (allowPartial === false && totalPaid > 0 && totalPaid < amount) {
            throw new BadRequestException(
                'This invoice does not allow partial payments — totalPaid must be either 0 or the full bill amount',
            );
        }
    }

    private async generateInvoiceNumber(): Promise<string> {
        const year = new Date().getFullYear();
        const prefix = `INV-${year}-`;

        for (let attempt = 0; attempt < 3; attempt++) {
            const count = await this.invoiceModel.countDocuments({
                invoiceNumber: { $regex: `^${prefix}\\d+$` },
            });

            const seq = count + 1 + attempt;
            const invoiceNumber = `${prefix}${String(seq).padStart(6, '0')}`;
            const exists = await this.invoiceModel.exists({ invoiceNumber });
            if (!exists) return invoiceNumber;
        }

        // Fallback: crypto-based unique invoice number
        return `${prefix}${crypto.randomBytes(4).toString('hex').toUpperCase()}`;
    }

    private async generatePaymentId(): Promise<string> {
        const year = new Date().getFullYear();
        const prefix = `PAY-${year}-`;

        for (let attempt = 0; attempt < 3; attempt++) {
            const count = await this.invoiceModel.countDocuments({
                paymentId: { $regex: `^${prefix}\\d+$` },
            });

            const seq = count + 1 + attempt;
            const paymentId = `${prefix}${String(seq).padStart(6, '0')}`;
            const exists = await this.invoiceModel.exists({ paymentId });
            if (!exists) return paymentId;
        }

        // Fallback: crypto-based unique payment ID
        return `${prefix}${crypto.randomBytes(4).toString('hex').toUpperCase()}`;
    }

    // Sequential receipt number for invoices (distinct from the fee-side receipt
    // space; fee-side uses the same RCPT-YYYY prefix but counts across
    // FeeAssignment + FeePayment). Number collisions across collections are
    // acceptable because each collection enforces its own unique index and
    // verify flows route by prefix. For manual invoices this ensures every
    // paid invoice has a receipt identifier even without a FeePayment record.
    private async generateReceiptNumber(): Promise<string> {
        const year = new Date().getFullYear();
        const prefix = `RCPT-${year}-`;

        for (let attempt = 0; attempt < 3; attempt++) {
            const count = await this.invoiceModel.countDocuments({
                receiptNumber: { $regex: `^${prefix}\\d+$` },
            });

            const seq = count + 1 + attempt;
            const receiptNumber = `${prefix}${String(seq).padStart(6, '0')}`;
            const exists = await this.invoiceModel.exists({ receiptNumber });
            if (!exists) return receiptNumber;
        }

        return `${prefix}${crypto.randomBytes(4).toString('hex').toUpperCase()}`;
    }

    // Auto-generated txn id (TXN-YYYY-NNNNNN) for when admin didn't capture a
    // real bank/UPI/cheque ref. Real refs supplied via DTO bypass this.
    private async generateTransactionId(): Promise<string> {
        const year = new Date().getFullYear();
        const prefix = `TXN-${year}-`;

        for (let attempt = 0; attempt < 3; attempt++) {
            const count = await this.invoiceModel.countDocuments({
                transactionId: { $regex: `^${prefix}\\d+$` },
            });

            const seq = count + 1 + attempt;
            const transactionId = `${prefix}${String(seq).padStart(6, '0')}`;
            const exists = await this.invoiceModel.exists({ transactionId });
            if (!exists) return transactionId;
        }

        return `${prefix}${crypto.randomBytes(4).toString('hex').toUpperCase()}`;
    }

    /** Escape regex special chars for safe MongoDB $regex usage */
    private escapeRegex(str: string): string {
        return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }

    /** Build a reusable filter query from DTO + academicYearId */
    private buildQuery(filter: FilterInvoicesDto, academicYearId?: string): Record<string, any> {
        const q: any = {};

        if (academicYearId) q.academicYearId = academicYearId;
        if (filter.classId) q.classId = filter.classId;
        if (filter.studentId) q.studentId = filter.studentId;
        if ((filter as any).isActive !== undefined) q.isActive = (filter as any).isActive;
        if (filter.status === 'overdue') {
            // Virtual status: not paid AND past dueDate.
            q.status = { $in: ['pending', 'partial'] };
            q.dueDate = { $lt: new Date() };
        } else if (filter.status) {
            q.status = filter.status;
        }

        if (filter.search) {
            const escaped = this.escapeRegex(filter.search);
            q.$or = [
                { studentName: { $regex: escaped, $options: 'i' } },
                { studentUniqueId: { $regex: escaped, $options: 'i' } },
                { invoiceNumber: { $regex: escaped, $options: 'i' } },
                { paymentId: { $regex: escaped, $options: 'i' } },
            ];
        }

        if (filter.dateFrom || filter.dateTo) {
            q.date = {};
            if (filter.dateFrom) q.date.$gte = new Date(filter.dateFrom);
            if (filter.dateTo) {
                const end = new Date(filter.dateTo);
                end.setHours(23, 59, 59, 999);
                q.date.$lte = end;
            }
        }

        return q;
    }

    // =====================
    //  CRUD
    // =====================

    async create(dto: CreateInvoiceDto, academicYearId?: string) {
        // Look up student
        const student = await this.studentModel
            .findById(dto.studentId, { name: 1, uniqueId: 1, classId: 1 })
            .lean() as any;
        if (!student) throw new NotFoundException('Student not found');

        // Validate student has a class assigned
        if (!student.classId) {
            throw new BadRequestException('Student does not have a class assigned');
        }

        // Validate totalPaid does not exceed amount
        const totalPaid = dto.totalPaid ?? 0;
        if (totalPaid > dto.amount) {
            throw new BadRequestException('Total paid cannot exceed invoice amount');
        }

        // Enforce the partial-payment policy on the first write.
        this.validatePartialRule(dto.allowPartialPayment, dto.amount, totalPaid);

        // Look up class name
        const cls = await this.classModel
            .findById(student.classId, { name: 1 })
            .lean() as any;

        const invoiceNumber = await this.generateInvoiceNumber();
        const paymentId = totalPaid > 0 ? await this.generatePaymentId() : undefined;
        // Auto-generate receipt + txn identifiers when the invoice is recorded
        // as already paid/partial. Admin-supplied transactionId (real bank/UPI
        // ref) wins; otherwise fall back to an auto-generated TXN.
        const receiptNumber = totalPaid > 0 ? await this.generateReceiptNumber() : undefined;
        const transactionId = totalPaid > 0
            ? (dto.transactionId?.trim() || await this.generateTransactionId())
            : undefined;
        const balance = Math.max(0, dto.amount - totalPaid);
        const status = this.deriveStatus(dto.amount, totalPaid);
        // Route is @Roles(Role.ADMIN)-gated, so caller is always an admin.
        const generatedBy = 'Admin';

        const invoice = await this.invoiceModel.create({
            invoiceNumber,
            paymentId,
            receiptNumber,
            transactionId,
            studentId: dto.studentId,
            studentName: student.name || '',
            studentUniqueId: student.uniqueId || '',
            classId: String(student.classId),
            className: cls?.name || '',
            academicYearId: academicYearId || '',
            amount: dto.amount,
            totalPaid,
            balance,
            status,
            paymentMode: dto.paymentMode,
            date: dto.date ? new Date(dto.date) : new Date(),
            dueDate: dto.dueDate ? new Date(dto.dueDate) : undefined,
            generatedBy,
            isActive: dto.isActive ?? true,
            notes: dto.notes?.trim() || undefined,
            allowPartialPayment: dto.allowPartialPayment,
        });

        return invoice.toObject();
    }

    async findAll(filter: FilterInvoicesDto, academicYearId?: string) {
        const q = this.buildQuery(filter, academicYearId);

        return this.invoiceModel
            .find(q)
            .sort({ date: -1 })
            .limit(5000)
            .lean({ virtuals: true });
    }

    async findOne(id: string) {
        const invoice = await this.invoiceModel.findById(id).lean({ virtuals: true });
        if (!invoice) throw new NotFoundException('Invoice not found');
        return invoice;
    }

    /** Student-scoped invoice lookup. Filters by ownership AND isActive so
     *  admin-deactivated rows stay hidden. */
    async findOneForStudent(invoiceId: string, studentId: string) {
        const inv = await this.invoiceModel
            .findOne({ _id: invoiceId, studentId, isActive: true })
            .lean({ virtuals: true });
        if (!inv) throw new NotFoundException('Invoice not found');
        return inv;
    }

    async createRazorpayOrder(invoiceId: string, studentId: string, amount?: number) {
        await this.refreshRazorpayCreds();
        const inv = await this.invoiceModel
            .findOne({ _id: invoiceId, studentId, isActive: true })
            .lean() as any;
        if (!inv) throw new NotFoundException('Invoice not found');
        if (inv.status === 'paid') throw new BadRequestException('Invoice already paid');

        const balance = Math.max(0, (inv.amount || 0) - (inv.totalPaid || 0));
        let orderAmount = balance;
        if (amount !== undefined && amount !== null) {
            if (amount < 1) throw new BadRequestException('Amount must be at least Rs 1');
            if (amount > balance) {
                throw new BadRequestException(`Amount exceeds remaining balance of ${balance}`);
            }
            orderAmount = amount;
        }
        if (orderAmount <= 0) throw new BadRequestException('Nothing to pay');

        // Enforce per-invoice partial-payment policy.
        const newTotalPaid = (inv.totalPaid || 0) + orderAmount;
        this.validatePartialRule(inv.allowPartialPayment, inv.amount, newTotalPaid);

        // Reuse existing order on exact amount-match (avoids dupes when student
        // closes the checkout sheet and re-opens it for the same amount).
        if (inv.razorpayOrderId && Math.abs((inv.razorpayOrderAmount || 0) - orderAmount) < 0.01) {
            return {
                orderId: inv.razorpayOrderId,
                amount: Math.round(orderAmount * 100),
                currency: 'INR',
                keyId: this.razorpayKeyId,
                invoiceId,
            };
        }

        let order: any;
        try {
            order = await this.getRazorpay().orders.create({
                amount: Math.round(orderAmount * 100),
                currency: 'INR',
                receipt: buildRazorpayReceipt('inv', invoiceId),
                // `type` lets any cross-flow webhook router identify invoice orders.
                notes: { invoiceId, studentId, type: 'invoice' },
            });
        } catch (err: any) {
            const reason = extractRazorpayErrorMessage(err);
            this.logger.error(`Razorpay order creation failed (invoice ${invoiceId}): ${reason}`, err?.stack || JSON.stringify(err));
            if (isRazorpayAuthError(err)) {
                throw new BadRequestException('Payment gateway authentication failed. Please verify the Razorpay Key ID and Key Secret in Settings.');
            }
            throw new ServiceUnavailableException(`Could not start payment: ${reason}`);
        }

        await this.invoiceModel.findByIdAndUpdate(invoiceId, {
            $set: {
                razorpayOrderId: order.id,
                razorpayOrderAmount: orderAmount,
            },
        });

        return {
            orderId: order.id,
            amount: order.amount,
            currency: order.currency,
            keyId: this.razorpayKeyId,
            invoiceId,
        };
    }

    async verifyRazorpayPayment(
        invoiceId: string,
        studentId: string,
        body: { razorpay_order_id: string; razorpay_payment_id: string; razorpay_signature: string },
    ) {
        await this.refreshRazorpayCreds();
        if (!this.razorpayKeySecret) {
            throw new BadRequestException('Online payments are not configured. Set Razorpay keys in Settings.');
        }
        // Signature verification — timing-safe compare.
        const expected = createHmac('sha256', this.razorpayKeySecret)
            .update(`${body.razorpay_order_id}|${body.razorpay_payment_id}`)
            .digest('hex');
        const sigBuf = Buffer.from(expected, 'hex');
        let provided: Buffer;
        try {
            provided = Buffer.from(body.razorpay_signature, 'hex');
        } catch {
            throw new BadRequestException('Invalid signature');
        }
        if (sigBuf.length !== provided.length || !timingSafeEqual(sigBuf, provided)) {
            throw new BadRequestException('Invalid signature');
        }

        const inv = await this.invoiceModel
            .findOne({ _id: invoiceId, studentId, razorpayOrderId: body.razorpay_order_id })
            .lean() as any;
        if (!inv) {
            throw new NotFoundException('Invoice not found or order mismatch');
        }
        const orderAmount = inv.razorpayOrderAmount || 0;
        if (orderAmount <= 0) {
            throw new BadRequestException('Order amount missing — please retry');
        }

        const newTotalPaid = (inv.totalPaid || 0) + orderAmount;
        if (newTotalPaid > inv.amount) {
            throw new BadRequestException('Overpayment detected');
        }
        // Defensive: re-check policy (frontend already restricts, but server is authoritative).
        this.validatePartialRule(inv.allowPartialPayment, inv.amount, newTotalPaid);

        const newStatus = this.deriveStatus(inv.amount, newTotalPaid);
        const balance = Math.max(0, inv.amount - newTotalPaid);

        const $set: Record<string, any> = {
            totalPaid: newTotalPaid,
            balance,
            status: newStatus,
            paymentMode: 'online',
            razorpayPaymentId: body.razorpay_payment_id,
            razorpaySignature: body.razorpay_signature,
        };
        // Auto-gen at first paid-transition only (existing IDs win).
        if (!inv.paymentId) $set.paymentId = await this.generatePaymentId();
        if (!inv.receiptNumber) $set.receiptNumber = await this.generateReceiptNumber();
        if (!inv.transactionId) $set.transactionId = body.razorpay_payment_id;
        // Stamp paidAt on first transition to 'paid' so the admin/student UI can
        // distinguish the payment moment from `date` (issue) / `dueDate`.
        if (newStatus === 'paid' && !(inv as any).paidAt) $set.paidAt = new Date();

        const updated = await this.invoiceModel.findOneAndUpdate(
            { _id: invoiceId, razorpayOrderId: body.razorpay_order_id },
            { $set, $unset: { razorpayOrderId: 1, razorpayOrderAmount: 1 } },
            { new: true },
        ).lean();

        if (!updated) {
            throw new BadRequestException('Payment already processed — please refresh');
        }
        return updated;
    }

    async update(id: string, dto: UpdateInvoiceDto) {
        const existing = await this.invoiceModel.findById(id).lean();
        if (!existing) throw new NotFoundException('Invoice not found');

        const $set: any = {};

        if (dto.amount !== undefined) $set.amount = dto.amount;
        if (dto.totalPaid !== undefined) $set.totalPaid = dto.totalPaid;
        if (dto.paymentMode !== undefined) $set.paymentMode = dto.paymentMode;
        if (dto.date !== undefined) $set.date = new Date(dto.date);
        if (dto.dueDate !== undefined) $set.dueDate = dto.dueDate ? new Date(dto.dueDate) : undefined;
        if (dto.notes !== undefined) $set.notes = dto.notes.trim();
        if (dto.isActive !== undefined) $set.isActive = dto.isActive;
        // Admin-supplied bank/UPI/cheque ref overrides any prior value.
        if (dto.transactionId !== undefined) {
            const trimmed = dto.transactionId.trim();
            if (trimmed) $set.transactionId = trimmed;
        }

        // Recompute balance and status
        const amount = $set.amount ?? existing.amount;
        const totalPaid = $set.totalPaid ?? existing.totalPaid;

        // Validate totalPaid does not exceed amount
        if (totalPaid > amount) {
            throw new BadRequestException('Total paid cannot exceed invoice amount');
        }

        // Enforce per-invoice partial-payment policy. existing.allowPartialPayment
        // may be undefined for legacy or fee-linked rows — helper interprets that
        // as "allowed" for backward compat.
        this.validatePartialRule(
            (existing as any).allowPartialPayment,
            amount,
            totalPaid,
        );

        $set.balance = Math.max(0, amount - totalPaid);
        $set.status = this.deriveStatus(amount, totalPaid);

        // Auto-generate paymentId/receiptNumber/transactionId when payment is
        // first recorded; unset them when totalPaid drops back to 0 (rare).
        const $unset: any = {};
        if (totalPaid > 0 && !existing.paymentId) {
            $set.paymentId = await this.generatePaymentId();
        } else if (totalPaid === 0 && existing.paymentId) {
            $unset.paymentId = 1;
        }
        if (totalPaid > 0 && !existing.receiptNumber) {
            $set.receiptNumber = await this.generateReceiptNumber();
        } else if (totalPaid === 0 && existing.receiptNumber) {
            $unset.receiptNumber = 1;
        }
        if (totalPaid > 0 && !existing.transactionId && !$set.transactionId) {
            $set.transactionId = await this.generateTransactionId();
        } else if (totalPaid === 0 && existing.transactionId && !$set.transactionId) {
            // Skip unset when admin is supplying a new value this update —
            // $set and $unset on the same path would conflict.
            $unset.transactionId = 1;
        }

        // Stamp/clear paidAt only on actual status transitions. Stamping on
        // every paid→paid update would falsely backfill legacy invoices (paid
        // months ago) with `now` whenever an admin edits notes/etc. For legacy
        // paid rows without paidAt, the listing UI shows '—' and the receipt
        // path falls back to `inv.date` — preferable to a wrong "now" stamp.
        if ($set.status === 'paid' && existing.status !== 'paid') {
            $set.paidAt = new Date();
        } else if ($set.status !== 'paid' && (existing as any).paidAt) {
            $unset.paidAt = 1;
        }

        const updateOps: any = { $set };
        if (Object.keys($unset).length > 0) updateOps.$unset = $unset;

        // Atomic guard: only set paymentId/receiptNumber if none exists yet
        // (prevents concurrent overwrite). We gate on paymentId as a proxy since
        // all three are generated together at the same transition boundary.
        // NOTE: must be findOneAndUpdate, not findByIdAndUpdate. Mongoose's
        // findByIdAndUpdate extracts only `_id` from a filter object and
        // silently drops the rest, so the guard would be ignored.
        const updateFilter: any = { _id: id };
        if ($set.paymentId) {
            updateFilter.paymentId = { $exists: false };
        }

        const updated = await this.invoiceModel.findOneAndUpdate(
            updateFilter,
            updateOps,
            { new: true },
        ).lean({ virtuals: true });

        if (!updated) {
            // Concurrent request already set paymentId — return current state
            const current = await this.invoiceModel.findById(id).lean({ virtuals: true });
            if (!current) throw new NotFoundException('Invoice not found');
            return current;
        }
        return updated;
    }

    async toggleActive(id: string) {
        const updated = await this.invoiceModel.findByIdAndUpdate(
            id,
            [{ $set: { isActive: { $not: '$isActive' } } }],
            { new: true, projection: { isActive: 1 } },
        ).lean();
        if (!updated) throw new NotFoundException('Invoice not found');
        return { _id: id, isActive: (updated as any).isActive };
    }

    // Public receipt verification. Accepts either the auto-generated
    // receiptNumber (RCPT-YYYY-NNNNNN), paymentId (PAY-...), transactionId
    // (TXN-...), or invoiceNumber (INV-...). Returns a public-safe shape so
    // the QR-scan verify page can confirm the invoice without leaking PII.
    async verifyReceipt(lookup: string) {
        const query = {
            $or: [
                { receiptNumber: lookup },
                { paymentId: lookup },
                { transactionId: lookup },
                { invoiceNumber: lookup },
            ],
        };
        const inv = await this.invoiceModel.findOne(query, {
            invoiceNumber: 1, paymentId: 1, receiptNumber: 1, transactionId: 1,
            studentName: 1, studentUniqueId: 1, className: 1,
            feeName: 1, installment: 1,
            amount: 1, fineAmount: 1, totalPaid: 1, balance: 1,
            status: 1, paymentMode: 1, date: 1, paidAt: 1,
        }).lean();
        if (!inv) return null;
        return {
            receiptNumber: inv.receiptNumber || inv.paymentId || inv.invoiceNumber,
            invoiceNumber: inv.invoiceNumber,
            transactionId: inv.transactionId,
            studentName: inv.studentName,
            studentId: inv.studentUniqueId,
            className: inv.className,
            feeName: inv.feeName || 'Invoice',
            installment: inv.installment || '',
            amount: inv.amount,
            fineAmount: inv.fineAmount || 0,
            totalPaid: inv.totalPaid,
            status: inv.status,
            // Legacy invoices may not have paidAt — fall back to issue date so
            // the receipt still shows a sensible date.
            paidAt: (inv as any).paidAt || inv.date,
            paymentMethod: inv.paymentMode,
        };
    }

    async delete(id: string) {
        const result = await this.invoiceModel.findByIdAndDelete(id);
        if (!result) throw new NotFoundException('Invoice not found');
        return { deleted: true };
    }

    /**
     * One-time maintenance: backfill the `paidAt` field on legacy invoices
     * that were marked paid before the field was introduced. Uses `updatedAt`
     * as the best available signal — for fresh paid invoices that's the
     * actual payment moment; for invoices later edited it'll be the last-edit
     * time, slightly off but in the right ballpark. Falls back to `date`
     * (issue date) if updatedAt is somehow missing.
     *
     * Safe to re-run: filter only matches paid rows that still lack `paidAt`,
     * so subsequent calls are no-ops once everything is backfilled.
     */
    async backfillPaidAt() {
        const result = await this.invoiceModel.updateMany(
            {
                status: 'paid',
                $or: [
                    { paidAt: { $exists: false } },
                    { paidAt: null },
                ],
            },
            [
                { $set: { paidAt: { $ifNull: ['$updatedAt', '$date'] } } },
            ],
        );
        return {
            matched: (result as any).matchedCount ?? 0,
            backfilled: result.modifiedCount ?? 0,
        };
    }

    async exportAll(filter: FilterInvoicesDto, academicYearId?: string) {
        const q = this.buildQuery(filter, academicYearId);

        return this.invoiceModel
            .find(q)
            .sort({ date: -1 })
            .limit(10000)
            .lean({ virtuals: true });
    }

    /**
     * Find-or-create an Invoice tied to a FeeAssignment. Called from the fees flow
     * after each successful FeePayment. On first call creates the Invoice; on subsequent
     * calls updates totalPaid/balance/status/paymentMode to reflect the latest cumulative state.
     */
    async upsertFromFeePayment(input: {
        feeAssignmentId: string;
        studentId: string;
        classId: string;
        academicYearId: string;
        billAmount: number;
        totalPaid: number;
        paymentMethod: string;
        generatedBy: string;
        feeName?: string;
        installment?: string;
        fineAmount?: number;
    }) {
        const billAmount = Math.max(0, input.billAmount);
        const totalPaid = Math.max(0, Math.min(input.totalPaid, billAmount));
        const balance = Math.max(0, billAmount - totalPaid);
        const status = this.deriveStatus(billAmount, totalPaid);
        // Invoice paymentMode is restricted to 'online' | 'offline'. Map the
        // fee-payment side's granular method (razorpay/cash/upi/cheque/etc.)
        // into one of the two buckets.
        const paymentMode: 'online' | 'offline' | undefined =
            (input.paymentMethod === 'razorpay' || input.paymentMethod === 'online')
                ? 'online'
                : (['cash', 'upi', 'cheque', 'bank_transfer', 'offline'].includes(input.paymentMethod)
                    ? 'offline'
                    : undefined);

        const existing = await this.invoiceModel
            .findOne({ feeAssignmentId: input.feeAssignmentId })
            .lean();

        if (existing) {
            const $set: Record<string, any> = {
                amount: billAmount,
                fineAmount: Math.max(0, input.fineAmount || 0),
                totalPaid,
                balance,
                status,
                date: new Date(),
            };
            if (paymentMode) $set.paymentMode = paymentMode;
            if (input.feeName && !existing.feeName) $set.feeName = input.feeName;
            if (input.installment && !existing.installment) $set.installment = input.installment;

            const updated = await this.invoiceModel.findByIdAndUpdate(
                existing._id,
                { $set },
                { new: true },
            ).lean({ virtuals: true });
            return updated;
        }

        // classId comes from the FeeAssignment (the caller), so invoice creation
        // no longer hinges on the student's current classId — which can be stale
        // after promotion/demotion/deactivation and was previously causing silent
        // invoice-creation skips for partial payments.
        const student = await this.studentModel
            .findById(input.studentId, { name: 1, uniqueId: 1 })
            .lean() as any;
        if (!student) {
            this.logger.warn(`upsertFromFeePayment: student ${input.studentId} not found — invoice skipped for assignment ${input.feeAssignmentId}`);
            return null;
        }

        const cls = await this.classModel
            .findById(input.classId, { name: 1 })
            .lean() as any;

        const invoiceNumber = await this.generateInvoiceNumber();
        const paymentId = totalPaid > 0 ? await this.generatePaymentId() : undefined;

        try {
            const invoice = await this.invoiceModel.create({
                invoiceNumber,
                paymentId,
                feeAssignmentId: input.feeAssignmentId,
                feeName: input.feeName,
                installment: input.installment,
                studentId: input.studentId,
                studentName: student.name || '',
                studentUniqueId: student.uniqueId || '',
                classId: input.classId,
                className: cls?.name || '',
                academicYearId: input.academicYearId,
                amount: billAmount,
                fineAmount: Math.max(0, input.fineAmount || 0),
                totalPaid,
                balance,
                status,
                paymentMode,
                generatedBy: input.generatedBy || 'System',
                isActive: true,
            });
            return invoice.toObject();
        } catch (err: any) {
            // Concurrent upsert — another call already created the invoice for this assignment.
            // Fetch and update it instead.
            if (err?.code === 11000) {
                const concurrent = await this.invoiceModel
                    .findOne({ feeAssignmentId: input.feeAssignmentId })
                    .lean();
                if (concurrent) {
                    const $set: Record<string, any> = {
                        amount: billAmount,
                        fineAmount: Math.max(0, input.fineAmount || 0),
                        totalPaid,
                        balance,
                        status,
                        date: new Date(),
                    };
                    if (paymentMode) $set.paymentMode = paymentMode;
                    return this.invoiceModel.findByIdAndUpdate(
                        concurrent._id,
                        { $set },
                        { new: true },
                    ).lean({ virtuals: true });
                }
            }
            throw err;
        }
    }
}
