"use server";

import { revalidatePath } from "next/cache";
import { connectDB } from "@/lib/db";
import { TimeEntry } from "@/models/TimeEntry";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession } from "@/lib/adminAuth";

const PATH = "/de/admin/zeiterfassung";

type FormState = { error?: string };

export async function clockInAction(): Promise<FormState> {
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) return { error: "Bitte einloggen." };

  await connectDB();
  const open = await TimeEntry.findOne({ clientId, clockOut: null }).select("_id").lean();
  if (open) return { error: "Du bist bereits eingestempelt." };

  try {
    await TimeEntry.create({ clientId, clockIn: new Date(), clockOut: null });
  } catch (err) {
    // Doppelklick/zwei offene Tabs kurz hintereinander — der partielle
    // unique-Index (siehe models/TimeEntry.ts) lässt nur einen offenen
    // Eintrag pro Mitarbeiter zu, das hier fängt genau diesen Fall sauber ab.
    if (err && typeof err === "object" && "code" in err && err.code === 11000) {
      return { error: "Du bist bereits eingestempelt." };
    }
    throw err;
  }

  revalidatePath(PATH);
  return {};
}

export async function clockOutAction(): Promise<FormState> {
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) return { error: "Bitte einloggen." };

  await connectDB();
  const open = await TimeEntry.findOne({ clientId, clockOut: null });
  if (!open) return { error: "Du bist nicht eingestempelt." };

  open.clockOut = new Date();
  await open.save();

  revalidatePath(PATH);
  return {};
}
