import { StockDirection } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { paginated, type Pagination } from '../../lib/pagination';
import { tenantHasFeature } from '../../middleware/requireFeature';

/**
 * Mess stock, kept as a ledger rather than a running total.
 *
 * Quantities are DERIVED from the entries, never stored on the item. A stored
 * balance and its ledger drift apart the first time a write half-fails, and
 * then nobody trusts either number.
 *
 * Quantities are held x100 so half a kilo of dal is exact — floats have no
 * business in a number people reconcile against a shop bill.
 */

export const QTY_SCALE = 100;

/** Every purchase also writes a MESS expense, so P&L cannot miss it. */
async function recordPurchaseExpense(input: { cost: number; date: Date; itemName: string; note?: string; recordedById: string; propertyId?: string }) {
  const tenantId = getTenantIdOrThrow();
  return db.expense.create({
    data: {
      tenantId,
      propertyId: input.propertyId,
      category: 'MESS',
      amount: input.cost,
      date: input.date,
      note: input.note ? `${input.itemName} — ${input.note}` : `Mess stock: ${input.itemName}`,
      recordedById: input.recordedById,
    },
  });
}

export async function listItems(
  filters?: { q?: string; needsReorder?: boolean },
  pagination?: Pagination | null,
) {
  const where = {
    isArchived: false,
    ...(filters?.q ? { name: { contains: filters.q, mode: 'insensitive' as const } } : {}),
  };

  // Every derived figure below — on hand, valuation, runway — is computed from
  // the entries, so the rows for a page are narrowed BEFORE their ledgers are
  // loaded. Fetching every entry for every item to show twenty of them is how
  // this list stops working once a mess has a year of purchases behind it.
  const page = pagination
    ? await db.messInventoryItem.findMany({
        where,
        select: { id: true },
        orderBy: { name: 'asc' },
        // needsReorder is derived from the ledger, so it cannot be a `where`.
        // Without a filter on it the page is exact; with one the rows are
        // narrowed after the fact, below.
        ...(filters?.needsReorder ? {} : { skip: pagination.skip, take: pagination.limit }),
      })
    : null;

  const items = await db.messInventoryItem.findMany({
    where: page ? { id: { in: page.map((p) => p.id) } } : where,
    include: { entries: { select: { direction: true, quantity: true, cost: true, date: true, reason: true } } },
    orderBy: { name: 'asc' },
  });

  const now = Date.now();
  const DAY = 86_400_000;
  const cutoff30 = new Date(now - 30 * DAY);

  const shaped = items.map(({ entries, ...item }) => {
    const ins = entries.filter((e) => e.direction === StockDirection.IN);
    const outs = entries.filter((e) => e.direction === StockDirection.OUT);
    const inQty = ins.reduce((n, e) => n + e.quantity, 0);
    const outQty = outs.reduce((n, e) => n + e.quantity, 0);
    const onHand = inQty - outQty;
    const spend = ins.reduce((n, e) => n + (e.cost ?? 0), 0);

    // Weighted average purchase cost, in rupees per unit. The valuation is
    // onHand × this — simple, and reconcilable against the shop bills.
    const avgUnitCost = inQty > 0 ? spend / (inQty / QTY_SCALE) : 0;

    // Consumption rate from USAGE outs (wastage and corrections are not
    // "use"). Averaged over the days actually OBSERVED — since the first
    // usage entry, capped at 30 — never over a flat month: an item cooked
    // from for two days would otherwise show a fifteenth of its real rate
    // and a runway of years.
    const usageOuts = outs.filter((e) => e.reason !== 'WASTAGE' && e.reason !== 'ADJUSTMENT');
    const firstUse = usageOuts.reduce<Date | null>((min, e) => (min === null || e.date < min ? e.date : min), null);
    const windowStart = firstUse && firstUse > cutoff30 ? firstUse : cutoff30;
    const windowDays = Math.min(30, Math.max(1, Math.ceil((now - windowStart.getTime()) / DAY)));
    const usedInWindow = usageOuts.filter((e) => e.date >= windowStart).reduce((n, e) => n + e.quantity, 0);
    const avgDailyUse = usedInWindow / windowDays / QTY_SCALE;

    // How long the shelf lasts at that rate. Null when there is no usage to
    // project from — a made-up number is worse than none.
    const runwayDays = avgDailyUse > 0 ? Math.floor(onHand / QTY_SCALE / avgDailyUse) : null;

    const wasted30 = outs.filter((e) => e.date >= cutoff30 && e.reason === 'WASTAGE').reduce((n, e) => n + e.quantity, 0);

    return {
      ...item,
      onHand: onHand / QTY_SCALE,
      reorderLevel: item.reorderLevel / QTY_SCALE,
      /** Below the level someone set — what the shopping list is built from. */
      needsReorder: item.reorderLevel > 0 && onHand <= item.reorderLevel,
      totalSpend: spend,
      avgUnitCost: Math.round(avgUnitCost * 100) / 100,
      stockValue: Math.round((onHand / QTY_SCALE) * avgUnitCost),
      avgDailyUse: Math.round(avgDailyUse * 100) / 100,
      runwayDays,
      wasted30: wasted30 / QTY_SCALE,
      /** Enough for ~30 days at the current rate, less what is on the shelf. */
      suggestedBuy: avgDailyUse > 0 ? Math.max(0, Math.ceil(avgDailyUse * 30 - onHand / QTY_SCALE)) : null,
      lastPurchase: ins.sort((a, b) => +b.date - +a.date)[0]?.date.toISOString().slice(0, 10) ?? null,
    };
  });

  if (!pagination) {
    return filters?.needsReorder ? shaped.filter((i) => i.needsReorder) : shaped;
  }

  // The shopping list asks for a derived field, so it is counted and paged
  // here rather than by the database. The set is small by construction — it
  // is what has run low, not the whole store.
  if (filters?.needsReorder) {
    const low = shaped.filter((i) => i.needsReorder);
    return paginated(
      low.slice(pagination.skip, pagination.skip + pagination.limit),
      low.length,
      pagination,
    );
  }

  return paginated(shaped, await db.messInventoryItem.count({ where }), pagination);
}

/**
 * The store's cards and shopping list for the whole store (Sprint L2): what
 * the clients used to add up from every item with its full ledger, plus the
 * newest 200 entries for the month's spend, which undercounted a busy month.
 * Summed by the database per item, with the same arithmetic as `listItems`,
 * so the cards agree with the rows. Money is zero where nobody keeps books
 * (Enterprise); quantities stay.
 */
export async function storeTotals() {
  const now = Date.now();
  const DAY = 86_400_000;
  const cutoff30 = new Date(now - 30 * DAY);
  const today = new Date(now);
  const monthStart = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), 1));
  const nextMonth = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth() + 1, 1));
  // A USAGE out, as `listItems` counts it: anything but wastage and corrections (a null reason too).
  const usage = { direction: StockDirection.OUT, OR: [{ reason: null }, { reason: { notIn: ['WASTAGE', 'ADJUSTMENT'] } }] };
  const live = { item: { isArchived: false } };

  const [items, sums, firstUse, used30, wasted30, month, books] = await Promise.all([
    db.messInventoryItem.findMany({ where: { isArchived: false }, select: { id: true, name: true, unit: true, reorderLevel: true }, orderBy: { name: 'asc' } }),
    db.messStockEntry.groupBy({ by: ['itemId', 'direction'], where: live, _sum: { quantity: true, cost: true } }),
    db.messStockEntry.groupBy({ by: ['itemId'], where: { ...live, ...usage }, _min: { date: true } }),
    db.messStockEntry.groupBy({ by: ['itemId'], where: { ...live, ...usage, date: { gte: cutoff30 } }, _sum: { quantity: true } }),
    db.messStockEntry.groupBy({ by: ['itemId'], where: { ...live, direction: StockDirection.OUT, reason: 'WASTAGE', date: { gte: cutoff30 } }, _sum: { quantity: true } }),
    db.messStockEntry.aggregate({ where: { direction: StockDirection.IN, date: { gte: monthStart, lt: nextMonth } }, _sum: { cost: true } }),
    tenantHasFeature(getTenantIdOrThrow(), 'expenses'),
  ]);

  const key = (id: string, d: StockDirection) => `${id}:${d}`;
  const sum = new Map(sums.map((s) => [key(s.itemId, s.direction), s._sum]));
  const first = new Map(firstUse.map((f) => [f.itemId, f._min.date]));
  const usedIn30 = new Map(used30.map((u) => [u.itemId, u._sum.quantity ?? 0]));
  const wastedIn30 = new Map(wasted30.map((w) => [w.itemId, w._sum.quantity ?? 0]));

  let stockValue = 0;
  let wastedValue = 0;
  const shoppingList: { id: string; name: string; unit: string; onHand: number; runwayDays: number | null; suggestedBuy: number | null }[] = [];
  for (const item of items) {
    const inQty = sum.get(key(item.id, StockDirection.IN))?.quantity ?? 0;
    const spend = sum.get(key(item.id, StockDirection.IN))?.cost ?? 0;
    const outQty = sum.get(key(item.id, StockDirection.OUT))?.quantity ?? 0;
    const onHand = inQty - outQty;
    const avgUnitCost = inQty > 0 ? spend / (inQty / QTY_SCALE) : 0;
    // Every usage entry is on or after the first, so usage since the window's
    // start is usage in the last 30 days — the window in `listItems`.
    const firstUse = first.get(item.id) ?? null;
    const windowStart = firstUse && firstUse > cutoff30 ? firstUse : cutoff30;
    const windowDays = Math.min(30, Math.max(1, Math.ceil((now - windowStart.getTime()) / DAY)));
    const avgDailyUse = (usedIn30.get(item.id) ?? 0) / windowDays / QTY_SCALE;
    stockValue += Math.round((onHand / QTY_SCALE) * avgUnitCost);
    wastedValue += Math.round(((wastedIn30.get(item.id) ?? 0) / QTY_SCALE) * (Math.round(avgUnitCost * 100) / 100));
    if (item.reorderLevel > 0 && onHand <= item.reorderLevel) {
      shoppingList.push({
        id: item.id,
        name: item.name,
        unit: item.unit,
        onHand: onHand / QTY_SCALE,
        runwayDays: avgDailyUse > 0 ? Math.floor(onHand / QTY_SCALE / avgDailyUse) : null,
        suggestedBuy: avgDailyUse > 0 ? Math.max(0, Math.ceil(avgDailyUse * 30 - onHand / QTY_SCALE)) : null,
      });
    }
  }
  return {
    items: items.length,
    lowCount: shoppingList.length,
    stockValue: books ? stockValue : 0,
    wastedValue: books ? wastedValue : 0,
    monthSpend: books ? month._sum.cost ?? 0 : 0,
    /** Items at or under their reorder level, in name order: the shopping list. */
    shoppingList,
  };
}

export async function createItem(input: { name: string; unit: string; reorderLevel?: number }) {
  const tenantId = getTenantIdOrThrow();
  const clash = await db.messInventoryItem.findFirst({ where: { name: input.name } });
  if (clash) throw new ConflictError(`"${input.name}" is already on the stock list`);
  return db.messInventoryItem.create({
    data: {
      tenantId,
      name: input.name,
      unit: input.unit,
      reorderLevel: Math.round((input.reorderLevel ?? 0) * QTY_SCALE),
    },
  });
}

export async function updateItem(id: string, input: { name?: string; unit?: string; reorderLevel?: number; isArchived?: boolean }) {
  const existing = await db.messInventoryItem.findFirst({ where: { id } });
  if (!existing) throw new NotFoundError('Item not found');
  if (input.name && input.name !== existing.name) {
    const clash = await db.messInventoryItem.findFirst({ where: { name: input.name, id: { not: id } } });
    if (clash) throw new ConflictError(`"${input.name}" is already on the stock list`);
  }
  return db.messInventoryItem.update({
    where: { id },
    data: {
      ...input,
      ...(input.reorderLevel !== undefined ? { reorderLevel: Math.round(input.reorderLevel * QTY_SCALE) } : {}),
    },
  });
}

/**
 * Archive rather than delete: the entries under an item are the mess's
 * purchase history, and deleting the item would orphan them.
 */
export async function archiveItem(id: string) {
  const existing = await db.messInventoryItem.findFirst({ where: { id } });
  if (!existing) throw new NotFoundError('Item not found');
  return db.messInventoryItem.update({ where: { id }, data: { isArchived: true } });
}

/**
 * Entries come back in the item's own unit and with a plain YYYY-MM-DD date.
 * The x100 scaling is a storage detail — leaking it made the ledger read
 * "bought 5000 kg of rice".
 */
function toPublicEntry<T extends { quantity: number; date: Date }>(entry: T) {
  return { ...entry, quantity: entry.quantity / QTY_SCALE, date: entry.date.toISOString().slice(0, 10) };
}

export async function listEntries(
  filters: { itemId?: string; from?: Date; to?: Date; direction?: StockDirection; q?: string },
  pagination?: Pagination | null,
) {
  const where = {
    ...(filters.itemId ? { itemId: filters.itemId } : {}),
    ...(filters.direction ? { direction: filters.direction } : {}),
    ...(filters.from || filters.to
      ? { date: { ...(filters.from ? { gte: filters.from } : {}), ...(filters.to ? { lte: filters.to } : {}) } }
      : {}),
    // The note and the item it moved — the two things someone remembers about
    // a movement they are looking for.
    ...(filters.q
      ? {
          OR: [
            { note: { contains: filters.q, mode: 'insensitive' as const } },
            { item: { is: { name: { contains: filters.q, mode: 'insensitive' as const } } } },
          ],
        }
      : {}),
  };
  const include = { item: { select: { id: true, name: true, unit: true } } };
  const orderBy = [{ date: 'desc' as const }, { createdAt: 'desc' as const }];

  if (!pagination) {
    const entries = await db.messStockEntry.findMany({ where, include, orderBy, take: 200 });
    return entries.map(toPublicEntry);
  }

  const [items, total] = await Promise.all([
    db.messStockEntry.findMany({ where, include, orderBy, skip: pagination.skip, take: pagination.limit }),
    db.messStockEntry.count({ where }),
  ]);
  return paginated(items.map(toPublicEntry), total, pagination);
}

export async function addEntry(input: {
  itemId: string;
  direction: StockDirection;
  quantity: number;
  cost?: number;
  reason?: string;
  date: Date;
  note?: string;
  recordedById: string;
  propertyId?: string;
}) {
  const tenantId = getTenantIdOrThrow();
  const item = await db.messInventoryItem.findFirst({ where: { id: input.itemId } });
  if (!item) throw new NotFoundError('Item not found');
  if (input.quantity <= 0) throw new BadRequestError('Quantity must be more than zero');
  // Where the operator keeps no books (Enterprise), a purchase is stock only.
  if (input.cost !== undefined && !(await tenantHasFeature(tenantId, 'expenses'))) input = { ...input, cost: undefined };
  if (input.direction === StockDirection.OUT && input.cost) {
    throw new BadRequestError('Only a purchase carries a cost — taking stock out does not');
  }
  if (input.direction === StockDirection.IN && input.reason) {
    throw new BadRequestError('A reason belongs on stock going out, not on a purchase');
  }

  const quantity = Math.round(input.quantity * QTY_SCALE);

  // A purchase is also money spent. Writing both here means the stock ledger
  // and the P&L can never tell different stories about the same groceries.
  let expenseId: string | undefined;
  if (input.direction === StockDirection.IN && input.cost && input.cost > 0) {
    const expense = await recordPurchaseExpense({
      cost: input.cost,
      date: input.date,
      itemName: item.name,
      note: input.note,
      recordedById: input.recordedById,
      propertyId: input.propertyId,
    });
    expenseId = expense.id;
  }

  const entry = await db.messStockEntry.create({
    data: {
      tenantId,
      itemId: input.itemId,
      direction: input.direction,
      quantity,
      cost: input.cost,
      reason: input.direction === StockDirection.OUT ? (input.reason ?? 'USAGE') : null,
      expenseId,
      date: input.date,
      note: input.note,
      recordedById: input.recordedById,
    },
    include: { item: { select: { id: true, name: true, unit: true } } },
  });
  return toPublicEntry(entry);
}

/**
 * Deleting an entry removes the expense it created too — otherwise correcting
 * a mistyped purchase would leave the money behind in the P&L.
 */
export async function deleteEntry(id: string) {
  const entry = await db.messStockEntry.findFirst({ where: { id } });
  if (!entry) throw new NotFoundError('Entry not found');
  await db.$transaction(async (tx) => {
    if (entry.expenseId) await tx.expense.deleteMany({ where: { id: entry.expenseId } });
    await tx.messStockEntry.delete({ where: { id } });
  });
}
