import "server-only";
import { prisma } from "@/lib/prisma";
import type { MeetingResponse } from "@prisma/client";

export type MeetingParticipantDTO = {
  id: string;
  name: string;
  avatarUrl: string | null;
  response: MeetingResponse;
};

export type MeetingDTO = {
  id: string;
  title: string;
  description: string | null;
  startAt: string;
  endAt: string;
  location: string | null;
  link: string | null;
  createdById: string;
  creatorName: string;
  participants: MeetingParticipantDTO[];
  myResponse: MeetingResponse | null;
};

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

/** Meetings, an denen der Nutzer beteiligt ist oder die er erstellt hat. */
export async function getMeetings(userId: string): Promise<MeetingDTO[]> {
  const rows = await prisma.meeting.findMany({
    where: { OR: [{ createdById: userId }, { participants: { some: { userId } } }] },
    orderBy: { startAt: "asc" },
    select: {
      id: true,
      title: true,
      description: true,
      startAt: true,
      endAt: true,
      location: true,
      link: true,
      createdById: true,
      creator: { select: { name: true, displayName: true } },
      participants: {
        select: { response: true, user: { select: { id: true, name: true, displayName: true, avatarUrl: true } } },
      },
    },
  });

  return rows.map((m) => ({
    id: m.id,
    title: m.title,
    description: m.description,
    startAt: m.startAt.toISOString(),
    endAt: m.endAt.toISOString(),
    location: m.location,
    link: m.link,
    createdById: m.createdById,
    creatorName: dn(m.creator),
    participants: m.participants.map((p) => ({
      id: p.user.id,
      name: dn(p.user),
      avatarUrl: p.user.avatarUrl,
      response: p.response,
    })),
    myResponse: m.participants.find((p) => p.user.id === userId)?.response ?? null,
  }));
}

export async function getMeetingUsers(): Promise<{ id: string; name: string; avatarUrl: string | null }[]> {
  const users = await prisma.user.findMany({
    where: { status: { not: "SUSPENDED" } },
    orderBy: { name: "asc" },
    select: { id: true, name: true, displayName: true, avatarUrl: true },
  });
  return users.map((u) => ({ id: u.id, name: dn(u), avatarUrl: u.avatarUrl }));
}

export type MeetingTeam = { id: string; name: string; color: string | null; memberIds: string[] };
export async function getMeetingTeams(): Promise<MeetingTeam[]> {
  const teams = await prisma.team.findMany({
    orderBy: { name: "asc" },
    select: { id: true, name: true, color: true, members: { select: { userId: true } } },
  });
  return teams.map((t) => ({ id: t.id, name: t.name, color: t.color, memberIds: t.members.map((m) => m.userId) }));
}
