import type { Company } from "@deadhead/schema"; import { eq, sql } from "drizzle-orm"; import type { Queryable } from "../db/client"; import { companies } from "../db/schema"; import { gameError } from "../http/errors"; import { requireCompany } from "./fleet"; /** * Pays the loan down by up to `amount` credits (decision 0.5.32): only the * balance is taken, and paying more than the player has fails with no change. * Run inside the player lock. */ export async function repayLoan(tx: Queryable, playerId: string, amount: number): Promise { const company = await requireCompany(tx, playerId); const payment = Math.min(amount, company.loanBalance); if (payment > company.credits) { throw gameError("insufficient-funds", `You only have ${company.credits} credits.`); } const [updated] = await tx .update(companies) .set({ credits: sql`${companies.credits} - ${payment}`, loanBalance: sql`${companies.loanBalance} - ${payment}`, }) .where(eq(companies.playerId, playerId)) .returning(); return { id: updated!.id, name: updated!.name, credits: updated!.credits, loanBalance: updated!.loanBalance, }; }