import { usePrisma } from "../utils/prisma";

export interface SosSessionInput {
  startedAt?: string | Date;
  endedAt?: string | Date | null;
  durationSec?: number | null;
  messages: Array<{ role: string; content: string; timestamp?: string }>;
  gamesPlayed?: Array<{ game: string; score?: number; durationSec?: number }>;
  breathingCount?: number;
  wasOvercome?: boolean;
  feedbackBetter?: boolean | null;
  feedbackRating?: number | null;
  feedbackText?: string | null;
  locale?: string | null;
}

export async function createSosSession(userId: string, input: SosSessionInput) {
  const db = usePrisma();
  return db.sosSession.create({
    data: {
      userId,
      startedAt: input.startedAt ? new Date(input.startedAt) : new Date(),
      endedAt: input.endedAt ? new Date(input.endedAt) : null,
      durationSec: input.durationSec ?? null,
      messages: input.messages as any,
      gamesPlayed: (input.gamesPlayed ?? []) as any,
      breathingCount: input.breathingCount ?? 0,
      wasOvercome: input.wasOvercome ?? false,
      feedbackBetter: input.feedbackBetter ?? null,
      feedbackRating: input.feedbackRating ?? null,
      feedbackText: input.feedbackText ?? null,
      locale: input.locale ?? null,
    },
    select: { id: true, startedAt: true, endedAt: true },
  });
}

export async function deleteUserSosSessions(userId: string) {
  const db = usePrisma();
  return db.sosSession.deleteMany({ where: { userId } });
}
