import { enqueueVoiceExperience } from '../hatchet/enqueue-voice-experience.js';
import { prisma } from '../prisma.js';

const forbiddenGeneratedPlaceIdPrefix = 'manual-';

export type CreateVoiceExperienceInput = {
  googlePlaceId: string;
  googleName: string;
  latitude: number;
  longitude: number;
  durationSeconds: number;
  audioObjectKey: string;
};

export async function createVoiceExperience(
  input: CreateVoiceExperienceInput,
  userId: string,
) {
  const googlePlaceId = input.googlePlaceId.trim();
  const googleName = input.googleName.trim();
  if (googlePlaceId === '') {
    throw new Error('Google place id is required.');
  }
  if (googlePlaceId.startsWith(forbiddenGeneratedPlaceIdPrefix)) {
    throw new Error('Voice experience must be linked to a Google place.');
  }
  if (googleName === '') {
    throw new Error('Google place name is required.');
  }

  const place = await prisma.place.upsert({
    where: { googlePlaceId },
    create: {
      googlePlaceId,
      name: googleName,
      latitude: input.latitude,
      longitude: input.longitude,
    },
    update: {
      name: googleName,
      latitude: input.latitude,
      longitude: input.longitude,
    },
  });

  const experience = await prisma.voiceExperience.create({
    data: {
      placeId: place.id,
      userId,
      durationSeconds: input.durationSeconds,
      audioObjectKey: input.audioObjectKey,
      status: 'UPLOADED',
    },
    include: { place: true, user: true },
  });

  await enqueueVoiceExperience({ experienceId: experience.id });

  return experience;
}
