import "server-only";
import { prisma } from "@/lib/prisma";
import type { ItemKind } from "./templates";
import type { ProtocolEntryStatus } from "@prisma/client";

// ──────────────────────────────────────────────────────────────────────────
// Lesezugriffe des Protokoll-Moduls.
// Entwürfe sieht nur, wer Einträge pflegen darf; alle anderen sehen
// ausschließlich veröffentlichte Einträge.
// ──────────────────────────────────────────────────────────────────────────

export type ProtocolDTO = {
  id: string;
  name: string;
  description: string | null;
  color: string | null;
  icon: string | null;
  entryCount: number;
  lastEntryAt: string | null;
  isOwner: boolean;
};

export type ProtocolItemDTO = { id: string; kind: ItemKind; text: string };

export type ProtocolEntryDTO = {
  id: string;
  protocolId: string;
  title: string;
  version: string | null;
  date: string;
  template: string;
  summary: string | null;
  status: ProtocolEntryStatus;
  authorName: string | null;
  isAuthor: boolean;
  updatedAt: string;
  items: ProtocolItemDTO[];
};

const dn = (u: { name: string; displayName: string | null } | null) =>
  u ? (u.displayName ?? u.name) : null;

export async function getProtocols(userId: string): Promise<ProtocolDTO[]> {
  const rows = await prisma.protocol.findMany({
    orderBy: [{ position: "asc" }, { createdAt: "asc" }],
    select: {
      id: true,
      name: true,
      description: true,
      color: true,
      icon: true,
      createdById: true,
      _count: { select: { entries: true } },
      entries: {
        take: 1,
        orderBy: { date: "desc" },
        select: { date: true },
      },
    },
  });

  return rows.map((p) => ({
    id: p.id,
    name: p.name,
    description: p.description,
    color: p.color,
    icon: p.icon,
    entryCount: p._count.entries,
    lastEntryAt: p.entries[0]?.date.toISOString() ?? null,
    isOwner: p.createdById === userId,
  }));
}

/** Einträge eines Protokolls — neueste zuerst. */
export async function getProtocolEntries(
  protocolId: string,
  userId: string,
  canManage: boolean,
): Promise<ProtocolEntryDTO[]> {
  const rows = await prisma.protocolEntry.findMany({
    where: {
      protocolId,
      ...(canManage ? {} : { status: "PUBLISHED" as const }),
    },
    orderBy: [{ date: "desc" }, { createdAt: "desc" }],
    select: {
      id: true,
      protocolId: true,
      title: true,
      version: true,
      date: true,
      template: true,
      summary: true,
      status: true,
      authorId: true,
      updatedAt: true,
      author: { select: { name: true, displayName: true } },
      items: {
        orderBy: [{ kind: "asc" }, { position: "asc" }],
        select: { id: true, kind: true, text: true },
      },
    },
  });

  return rows.map((e) => ({
    id: e.id,
    protocolId: e.protocolId,
    title: e.title,
    version: e.version,
    date: e.date.toISOString(),
    template: e.template,
    summary: e.summary,
    status: e.status,
    authorName: dn(e.author),
    isAuthor: e.authorId === userId,
    updatedAt: e.updatedAt.toISOString(),
    items: e.items.map((i) => ({ id: i.id, kind: i.kind as ItemKind, text: i.text })),
  }));
}
