import { db } from '../../lib/prisma';
import { getTenantIdOrThrow as tenantId } from '../../lib/tenantContext';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';

/**
 * The categories every tenant starts with. Codes, not labels — existing data
 * uses them, P&L groups by them, and the client renders friendly names.
 * Tenants extend the list with their own labels, stored on TenantSettings.
 */
export const BUILTIN_EXPENSE_CATEGORIES = [
  'MESS',
  'MAINTENANCE',
  'UTILITIES',
  'SALARY',
  'RENT_LEASE',
  'INTERNET',
  'CLEANING',
  'LAUNDRY',
  'SECURITY',
  'TRANSPORT',
  'MARKETING',
  'TAXES_FEES',
  'OTHER',
] as const;

export async function listCategories() {
  const settings = await db.tenantSettings.findFirst({ select: { expenseCategories: true } });
  return { builtin: [...BUILTIN_EXPENSE_CATEGORIES], custom: settings?.expenseCategories ?? [] };
}

async function allowedCategories(): Promise<Set<string>> {
  const { builtin, custom } = await listCategories();
  return new Set([...builtin, ...custom]);
}

/** A category must exist before money is filed under it — a typo'd category
 *  is a bucket nobody will ever look in. */
async function assertKnownCategory(category: string) {
  if (!(await allowedCategories()).has(category)) {
    throw new BadRequestError(`"${category}" is not one of your expense categories. Add it first.`);
  }
}

export async function addCategory(name: string) {
  const trimmed = name.trim();
  const { builtin, custom } = await listCategories();
  const clash = [...builtin, ...custom].some((c) => c.toLowerCase() === trimmed.toLowerCase());
  if (clash) throw new ConflictError(`"${trimmed}" already exists`);
  if (custom.length >= 20) throw new BadRequestError('That is 20 custom categories — remove one before adding more');

  const settings = await db.tenantSettings.findFirst({});
  if (settings) {
    await db.tenantSettings.update({ where: { id: settings.id }, data: { expenseCategories: [...custom, trimmed] } });
  } else {
    await db.tenantSettings.create({ data: { tenantId: tenantId(), expenseCategories: [trimmed] } });
  }
  return listCategories();
}

/**
 * Removing a custom category only takes it off the picker. Expenses already
 * filed under it keep their label — history is not rewritten by tidying a menu.
 */
export async function removeCategory(name: string) {
  const settings = await db.tenantSettings.findFirst({});
  const custom = settings?.expenseCategories ?? [];
  if (!settings || !custom.includes(name)) throw new NotFoundError('No such custom category');
  await db.tenantSettings.update({ where: { id: settings.id }, data: { expenseCategories: custom.filter((c) => c !== name) } });
  return listCategories();
}
import { monthRange } from '../../lib/period';
import { paginated, type Pagination } from '../../lib/pagination';

export async function createExpense(
  input: { category: string; amount: number; date: string; note?: string },
  recordedById: string,
  propertyId?: string,
) {
  await assertKnownCategory(input.category);
  return db.expense.create({
    data: {
      tenantId: tenantId(),
      propertyId,
      category: input.category,
      amount: input.amount,
      date: new Date(input.date),
      note: input.note,
      recordedById,
    },
  });
}

export async function listExpenses(
  period?: string,
  propertyId?: string,
  pagination?: Pagination | null,
  q?: string,
  category?: string,
) {
  const where = {
    ...(period ? monthWhere(period) : {}),
    ...(propertyId ? { propertyId } : {}),
    // Narrowing here rather than in the client: a page holds 20 of what can be
    // hundreds of rows, so filtering the page would hide most matches and make
    // the count line disagree with the list.
    ...(category ? { category } : {}),
    // Search the note, the only free text an expense carries.
    ...(q ? { note: { contains: q, mode: 'insensitive' as const } } : {}),
  };
  const orderBy = { date: 'desc' as const };

  // An expense written by a mess stock purchase belongs to that ledger, not to
  // this page's edit buttons — the client needs to know which rows those are.
  // Tagged after the rows are fetched, so a page looks up only its own rows.
  const tagSource = async <T extends { id: string }>(rows: T[]) => {
    const linked = await db.messStockEntry.findMany({
      where: { expenseId: { in: rows.map((e) => e.id) } },
      select: { expenseId: true },
    });
    const linkedIds = new Set(linked.map((l) => l.expenseId));
    return rows.map((e) => ({
      ...e,
      source: linkedIds.has(e.id) ? ('MESS_STORE' as const) : ('MANUAL' as const),
    }));
  };

  if (!pagination) return tagSource(await db.expense.findMany({ where, orderBy }));

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

/** Refuse to touch an expense a mess stock purchase created — the stock entry
 *  owns it, and editing here would make stock and P&L tell different stories. */
async function assertNotStockLinked(expenseId: string) {
  const linked = await db.messStockEntry.findFirst({ where: { expenseId } });
  if (linked) {
    throw new ConflictError(
      'This expense was created by a mess stock purchase. Correct it from Mess → Store — the stock entry and the money move together.',
      'EXPENSE_FROM_STOCK',
    );
  }
}

export async function updateExpense(
  id: string,
  input: { category?: string; amount?: number; date?: string; note?: string | null },
) {
  const existing = await db.expense.findFirst({ where: { id } });
  if (!existing) throw new NotFoundError('Expense not found');
  await assertNotStockLinked(id);
  if (input.category) await assertKnownCategory(input.category);
  return db.expense.update({
    where: { id },
    data: { ...input, ...(input.date ? { date: new Date(input.date) } : {}) },
  });
}

export async function deleteExpense(id: string) {
  const existing = await db.expense.findFirst({ where: { id } });
  if (!existing) throw new NotFoundError('Expense not found');
  await assertNotStockLinked(id);
  await db.expense.delete({ where: { id } });
}

function monthWhere(period: string) {
  const { start, end } = monthRange(period);
  return { date: { gte: start, lte: end } };
}

/**
 * Monthly P&L (cash basis): income = payments received in the month (split by
 * invoice type), expenses = expenses dated in the month (by category),
 * plus outstanding dues (unpaid invoices for the period).
 */
export async function getPnl(period: string, propertyId?: string) {
  const { start, end } = monthRange(period);

  // When a property is active, only that property's students count toward income.
  const studentFilter = propertyId ? { invoice: { student: { propertyId } } } : {};
  const payments = await db.payment.findMany({
    where: { paidAt: { gte: start, lte: end }, ...studentFilter },
    include: { invoice: { select: { type: true } } },
  });
  const rentCollected = payments.filter((p) => p.invoice.type === 'RENT').reduce((n, p) => n + p.amount, 0);
  const messCollected = payments.filter((p) => p.invoice.type === 'MESS').reduce((n, p) => n + p.amount, 0);
  const income = rentCollected + messCollected;

  const expenses = await db.expense.findMany({ where: { ...monthWhere(period), ...(propertyId ? { propertyId } : {}) } });
  const expenseByCategory: Record<string, number> = {};
  for (const e of expenses) expenseByCategory[e.category] = (expenseByCategory[e.category] ?? 0) + e.amount;
  const totalExpenses = expenses.reduce((n, e) => n + e.amount, 0);

  // Outstanding is what is still owed, so a part-paid invoice counts its
  // balance, not its face value.
  const pending = await db.invoice.findMany({
    where: { periodMonth: period, status: { not: 'PAID' }, ...(propertyId ? { student: { propertyId } } : {}) },
    select: { amount: true, payments: { where: { status: 'CLEARED' }, select: { amount: true } } },
  });
  const outstanding = pending.reduce((n, i) => n + Math.max(0, i.amount - i.payments.reduce((m, p) => m + p.amount, 0)), 0);

  return {
    period,
    income: { rent: rentCollected, mess: messCollected, total: income },
    expenses: { byCategory: expenseByCategory, total: totalExpenses },
    net: income - totalExpenses,
    outstandingDues: outstanding,
  };
}
