import { BadRequestException, Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { Model, Types } from "mongoose";
import { Batch, BatchDocument } from "./schemas/batch.schema";
import { InventoryBalance, InventoryBalanceDocument } from "./schemas/inventory-balance.schema";
import { Item, ItemDocument } from "./schemas/item.schema";
import {
  AdjustmentLine,
  StockAdjustment,
  StockAdjustmentDocument,
} from "./schemas/stock-adjustment.schema";
import { Vendor, VendorDocument } from "./schemas/vendor.schema";
import { Warehouse, WarehouseDocument } from "./schemas/warehouse.schema";
import { NotificationsService } from "./notifications.service";

const GLOBAL_MT_THRESHOLD = 26000;

@Injectable()
export class StockAdjustmentsService {
  constructor(
    @InjectModel(StockAdjustment.name)
    private readonly adjustmentModel: Model<StockAdjustmentDocument>,
    @InjectModel(Warehouse.name)
    private readonly warehouseModel: Model<WarehouseDocument>,
    @InjectModel(Item.name)
    private readonly itemModel: Model<ItemDocument>,
    @InjectModel(Batch.name)
    private readonly batchModel: Model<BatchDocument>,
    @InjectModel(InventoryBalance.name)
    private readonly balanceModel: Model<InventoryBalanceDocument>,
    @InjectModel(Vendor.name)
    private readonly vendorModel: Model<VendorDocument>,
    private readonly notificationsService: NotificationsService,
  ) {}

  // ── Create ────────────────────────────────────────────────────────────────

  async create(payload: {
    voucher?: string;
    vendorId?: string;
    adjustmentIn: Array<{
      warehouseId: string;
      itemId: string;
      batchNumber: string;
      expiryDate?: string;
      productionDate?: string;
      quantityMt: number;
    }>;
    adjustmentOut: Array<{
      warehouseId: string;
      itemId: string;
      batchId: string;
      quantityMt: number;
    }>;
    submittedBy?: string;
  }) {
    const adjIn = payload.adjustmentIn ?? [];
    const adjOut = payload.adjustmentOut ?? [];
    if (adjIn.length === 0 && adjOut.length === 0) {
      throw new BadRequestException("At least one Adjustment In or Adjustment Out line is required");
    }

    let vendor: { name: string } | null = null;
    if (payload.vendorId) {
      vendor = await this.vendorModel.findById(payload.vendorId).lean().exec();
      if (!vendor) throw new BadRequestException("Vendor not found");
    }

    adjIn.forEach((line, idx) => {
      if (!line.warehouseId) throw new BadRequestException(`Adjustment In line ${idx + 1}: warehouseId is required`);
      if (!line.itemId) throw new BadRequestException(`Adjustment In line ${idx + 1}: itemId is required`);
      if (!line.batchNumber) throw new BadRequestException(`Adjustment In line ${idx + 1}: batch number is required`);
      if (!line.quantityMt || line.quantityMt <= 0) {
        throw new BadRequestException(`Adjustment In line ${idx + 1}: quantityMt must be greater than 0`);
      }
    });

    const adjustmentIn: AdjustmentLine[] = await Promise.all(
      adjIn.map(async (line) => {
        const batch = await this._findOrCreateBatch(
          line.warehouseId,
          line.itemId,
          line.batchNumber,
          line.expiryDate ?? "",
          line.productionDate ?? null,
        );
        return {
          warehouseId: new Types.ObjectId(line.warehouseId),
          itemId: new Types.ObjectId(line.itemId),
          batchId: batch._id as Types.ObjectId,
          batchNumber: line.batchNumber,
          expiryDate: line.expiryDate ?? null,
          productionDate: line.productionDate ?? null,
          quantityMt: line.quantityMt,
        };
      }),
    );

    const adjustmentOut: AdjustmentLine[] = await Promise.all(
      adjOut.map(async (o, idx) => {
        if (!o.warehouseId) throw new BadRequestException(`Adjustment Out line ${idx + 1}: warehouseId is required`);
        if (!o.itemId) throw new BadRequestException(`Adjustment Out line ${idx + 1}: itemId is required`);
        if (!o.batchId) throw new BadRequestException(`Adjustment Out line ${idx + 1}: batchId is required`);
        if (!o.quantityMt || o.quantityMt <= 0) {
          throw new BadRequestException(`Adjustment Out line ${idx + 1}: quantityMt must be greater than 0`);
        }
        const batch = await this.batchModel.findById(o.batchId).lean().exec();
        if (!batch) throw new BadRequestException(`Adjustment Out line ${idx + 1}: batch not found`);

        return {
          warehouseId: new Types.ObjectId(o.warehouseId),
          itemId: new Types.ObjectId(o.itemId),
          batchId: new Types.ObjectId(o.batchId),
          batchNumber: batch.batchNumber,
          expiryDate: batch.expiryDate ?? null,
          productionDate: batch.productionDate ?? null,
          quantityMt: o.quantityMt,
        };
      }),
    );

    const totalInMt = Number(adjustmentIn.reduce((s, l) => s + l.quantityMt, 0).toFixed(4));
    const totalOutMt = Number(adjustmentOut.reduce((s, l) => s + l.quantityMt, 0).toFixed(4));

    const adjustment = await this.adjustmentModel.create({
      voucher: payload.voucher?.trim() || null,
      vendorId: payload.vendorId ? new Types.ObjectId(payload.vendorId) : null,
      vendor: vendor?.name ?? null,
      adjustmentIn,
      adjustmentOut,
      totalInMt,
      totalOutMt,
      approvalStatus: "pending_approval",
      submittedBy: payload.submittedBy ?? null,
      createdAt: new Date().toISOString(),
    });

    await this.notificationsService.notifyManagers(
      `New Stock Adjustment (${totalInMt} MT in / ${totalOutMt} MT out) is pending your approval.`,
      (adjustment._id as Types.ObjectId).toString(),
    );

    return this._mapAdjustment(adjustment.toObject());
  }

  // ── Read ──────────────────────────────────────────────────────────────────

  async findAll(params?: { status?: string; page?: number; limit?: number }) {
    const query: Record<string, unknown> = {};
    if (params?.status) query.approvalStatus = params.status;

    let queryBuilder = this.adjustmentModel.find(query).sort({ createdAt: -1 });
    if (params?.page && params?.limit) {
      queryBuilder = queryBuilder.skip((params.page - 1) * params.limit).limit(params.limit);
    }

    const adjustments = await queryBuilder.lean().exec();
    return Promise.all(adjustments.map((a) => this._mapAdjustmentWithDetails(a)));
  }

  async findOne(id: string) {
    const adjustment = await this.adjustmentModel.findById(id).lean().exec();
    if (!adjustment) throw new BadRequestException("Adjustment not found");
    return this._mapAdjustmentWithDetails(adjustment);
  }

  // ── Approve ───────────────────────────────────────────────────────────────

  async approve(id: string, approvedByName: string) {
    const adjustment = await this.adjustmentModel.findById(id).exec();
    if (!adjustment) throw new BadRequestException("Adjustment not found");
    if (adjustment.approvalStatus !== "pending_approval") {
      throw new BadRequestException("Adjustment is not pending approval");
    }

    // Validate every Adjustment Out leg has sufficient balance before mutating anything
    for (const line of adjustment.adjustmentOut as AdjustmentLine[]) {
      const balance = await this.balanceModel.findOne({ batchId: line.batchId }).exec();
      if (!balance || balance.currentQuantityMt < line.quantityMt) {
        throw new BadRequestException(
          `Insufficient inventory for batch ${line.batchNumber}. Available: ${balance?.currentQuantityMt ?? 0} MT, Requested: ${line.quantityMt} MT`,
        );
      }
    }

    for (const line of adjustment.adjustmentIn as AdjustmentLine[]) {
      await this._applyBalanceDelta(
        line.warehouseId.toString(),
        line.itemId.toString(),
        line.batchId.toString(),
        line.quantityMt,
        "inbound",
      );
    }

    for (const line of adjustment.adjustmentOut as AdjustmentLine[]) {
      await this._applyBalanceDelta(
        line.warehouseId.toString(),
        line.itemId.toString(),
        line.batchId.toString(),
        line.quantityMt,
        "outbound",
      );
    }

    adjustment.approvalStatus = "approved";
    adjustment.approvedBy = approvedByName;
    adjustment.approvedAt = new Date().toISOString();
    await adjustment.save();

    return this._mapAdjustment(adjustment.toObject());
  }

  // ── Reject ────────────────────────────────────────────────────────────────

  async reject(id: string, rejectedByName: string, reason: string) {
    const adjustment = await this.adjustmentModel.findById(id).exec();
    if (!adjustment) throw new BadRequestException("Adjustment not found");
    if (adjustment.approvalStatus !== "pending_approval") {
      throw new BadRequestException("Adjustment is not pending approval");
    }

    adjustment.approvalStatus = "rejected";
    adjustment.rejectedBy = rejectedByName;
    adjustment.rejectedAt = new Date().toISOString();
    adjustment.rejectedReason = reason ?? "";
    await adjustment.save();

    return this._mapAdjustment(adjustment.toObject());
  }

  // ── Private helpers ───────────────────────────────────────────────────────

  private async _findOrCreateBatch(
    warehouseId: string,
    itemId: string,
    batchNumber: string,
    expiryDate: string,
    productionDate: string | null = null,
  ) {
    const existing = await this.batchModel
      .findOne({
        warehouseId: new Types.ObjectId(warehouseId),
        itemId: new Types.ObjectId(itemId),
        batchNumber,
      })
      .exec();
    if (existing) {
      if (expiryDate) {
        existing.expiryDate = expiryDate;
        await existing.save();
      }
      return existing;
    }
    return this.batchModel.create({
      warehouseId: new Types.ObjectId(warehouseId),
      itemId: new Types.ObjectId(itemId),
      batchNumber,
      expiryDate: expiryDate || "2099-12-31",
      productionDate,
    });
  }

  private async _applyBalanceDelta(
    warehouseId: string,
    itemId: string,
    batchId: string,
    quantityMt: number,
    type: "inbound" | "outbound",
  ) {
    let balance = await this.balanceModel.findOne({ batchId: new Types.ObjectId(batchId) }).exec();
    if (!balance) {
      balance = await this.balanceModel.create({
        warehouseId: new Types.ObjectId(warehouseId),
        itemId: new Types.ObjectId(itemId),
        batchId: new Types.ObjectId(batchId),
        currentQuantityMt: 0,
        thresholdTargetMt: GLOBAL_MT_THRESHOLD,
        lastUpdated: new Date().toISOString(),
      });
    }

    const delta = type === "inbound" ? quantityMt : -quantityMt;
    balance.currentQuantityMt = Math.max(0, balance.currentQuantityMt + delta);
    balance.lastUpdated = new Date().toISOString();
    await balance.save();

    if (type === "outbound" && balance.currentQuantityMt === 0) {
      const batch = await this.batchModel.findById(batchId).exec();
      if (batch) {
        batch.stockedOut = true;
        await batch.save();
      }
    }
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  private _mapAdjustment(a: any) {
    return {
      id: (a._id as Types.ObjectId)?.toString() ?? a.id,
      voucher: a.voucher ?? null,
      vendorId: a.vendorId?.toString() ?? null,
      vendor: a.vendor ?? null,
      adjustmentIn: (a.adjustmentIn ?? []).map((line: AdjustmentLine) => ({
        warehouseId: line.warehouseId?.toString(),
        itemId: line.itemId?.toString(),
        batchId: line.batchId?.toString(),
        batchNumber: line.batchNumber,
        expiryDate: line.expiryDate ?? null,
        productionDate: line.productionDate ?? null,
        quantityMt: line.quantityMt,
      })),
      adjustmentOut: (a.adjustmentOut ?? []).map((line: AdjustmentLine) => ({
        warehouseId: line.warehouseId?.toString(),
        itemId: line.itemId?.toString(),
        batchId: line.batchId?.toString(),
        batchNumber: line.batchNumber,
        expiryDate: line.expiryDate ?? null,
        productionDate: line.productionDate ?? null,
        quantityMt: line.quantityMt,
      })),
      totalInMt: a.totalInMt ?? 0,
      totalOutMt: a.totalOutMt ?? 0,
      approvalStatus: a.approvalStatus,
      approvedBy: a.approvedBy ?? null,
      approvedAt: a.approvedAt ?? null,
      rejectedBy: a.rejectedBy ?? null,
      rejectedAt: a.rejectedAt ?? null,
      rejectedReason: a.rejectedReason ?? null,
      submittedBy: a.submittedBy ?? null,
      createdAt: a.createdAt,
    };
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  private async _mapAdjustmentWithDetails(a: any) {
    const base = this._mapAdjustment(a);

    async function detail(this_: StockAdjustmentsService, line: { warehouseId: string; itemId: string; batchNumber: string }) {
      const [item, warehouse] = await Promise.all([
        this_.itemModel.findById(line.itemId).lean().exec(),
        this_.warehouseModel.findById(line.warehouseId).lean().exec(),
      ]);
      return {
        itemCode: item?.itemCode ?? null,
        itemName: item?.itemName ?? item?.description ?? null,
        warehouseName: warehouse?.name ?? null,
      };
    }

    type MappedLine = ReturnType<typeof this._mapAdjustment>["adjustmentIn"][number];
    const adjustmentInDetailed = await Promise.all(
      base.adjustmentIn.map(async (line: MappedLine) => ({ ...line, ...(await detail(this, line)) })),
    );
    const adjustmentOutDetailed = await Promise.all(
      base.adjustmentOut.map(async (line: MappedLine) => ({ ...line, ...(await detail(this, line)) })),
    );

    return {
      ...base,
      // Back-compat top-level fields for the first line — the list table
      // shows one summary row per adjustment and reads these.
      firstItemCode: adjustmentInDetailed[0]?.itemCode ?? adjustmentOutDetailed[0]?.itemCode ?? null,
      firstItemName: adjustmentInDetailed[0]?.itemName ?? adjustmentOutDetailed[0]?.itemName ?? null,
      adjustmentIn: adjustmentInDetailed,
      adjustmentOut: adjustmentOutDetailed,
    };
  }
}
