import { and, eq, lt } from "drizzle-orm";
import * as schema from "./schema/index.js";

const SESSION_TIMEOUT_MS = 24 * 60 * 60 * 1000;

/**
 * Timeout-jobb (Fas 3 §6 / §20): avbryt STARTED-sessioner äldre än 24 h utan complete.
 * PLANNED reserverar aldrig lager, så den behöver ingen timeout.
 */
export async function cancelTimedOutCookingSessions(db: { update: Function }) {
  const deadline = new Date(Date.now() - SESSION_TIMEOUT_MS);
  const sessions = await db
    .update(schema.cookingSessions)
    .set({ status: "cancelled", cancelledAt: new Date(), updatedAt: new Date() })
    .where(
      and(
        eq(schema.cookingSessions.status, "started"),
        lt(schema.cookingSessions.startedAt, deadline),
      ),
    )
    .returning();
  return sessions;
}
