import { prisma } from '@/lib/db';

export interface ListActionsFilters {
  conversationId?: string;
  status?: string;
  assignedTo?: string;
  limit?: number;
  offset?: number;
}

export interface CreateActionInput {
  conversationId: string;
  type: string;
  title: string;
  description?: string;
  dueAt?: string;
  assignedTo?: string;
  metadata?: Record<string, unknown>;
}

export interface UpdateActionInput {
  status?: string;
  title?: string;
  description?: string | null;
  dueAt?: string | null;
  assignedTo?: string | null;
  metadata?: Record<string, unknown>;
}

function isVoicePlatform(platform: string | null | undefined): boolean {
  const normalized = (platform || '').toLowerCase();
  return normalized.includes('voice');
}

export async function listActions(filters: ListActionsFilters) {
  const where: Record<string, unknown> = {};

  if (filters.conversationId) {
    where.conversationId = filters.conversationId;
  }
  if (filters.status) {
    where.status = filters.status;
  }
  if (filters.assignedTo) {
    where.assignedTo = filters.assignedTo;
  }

  const limit = filters.limit ?? 50;
  const offset = filters.offset ?? 0;

  const [actions, total] = await prisma.$transaction([
    prisma.voiceConversationAction.findMany({
      where,
      orderBy: { createdAt: 'desc' },
      take: limit,
      skip: offset,
    }),
    prisma.voiceConversationAction.count({ where }),
  ]);

  return { actions, total };
}

export async function createAction(data: CreateActionInput, _staffId: string) {
  const conversation = await prisma.conversationLog.findUnique({
    where: { id: data.conversationId },
    select: { id: true, platform: true },
  });

  if (!conversation) {
    throw new Error('Conversation not found');
  }

  if (!isVoicePlatform(conversation.platform)) {
    throw new Error('Actions can only be created for voice conversations');
  }

  return prisma.voiceConversationAction.create({
    data: {
      conversationId: data.conversationId,
      type: data.type,
      title: data.title,
      description: data.description ?? null,
      dueAt: data.dueAt ? new Date(data.dueAt) : null,
      assignedTo: data.assignedTo ?? null,
      metadata: (data.metadata ?? null) as any,
      status: 'PENDING',
      completedAt: null,
      completedBy: null,
      updatedAt: new Date(),
    },
  });
}

export async function getActionById(actionId: string) {
  return prisma.voiceConversationAction.findUnique({
    where: { id: actionId },
  });
}

export async function updateAction(
  actionId: string,
  updates: UpdateActionInput,
  staffId: string
) {
  const existing = await prisma.voiceConversationAction.findUnique({
    where: { id: actionId },
  });

  if (!existing) {
    throw new Error('Action not found');
  }

  const data: Record<string, unknown> = {
    ...updates,
    dueAt: updates.dueAt ? new Date(updates.dueAt) : updates.dueAt === null ? null : undefined,
    updatedAt: new Date(),
  };

  if (updates.status === 'COMPLETED') {
    data.completedAt = new Date();
    data.completedBy = staffId;
  }

  return prisma.voiceConversationAction.update({
    where: { id: actionId },
    data,
  });
}

export async function getConversationWithTranscript(conversationId: string) {
  const conversation = await prisma.conversationLog.findUnique({
    where: { id: conversationId },
    include: {
      conversationLogMessages: {
        orderBy: { timestamp: 'asc' },
      },
      voiceActions: {
        orderBy: { createdAt: 'desc' },
      },
    },
  });

  if (!conversation) {
    return null;
  }

  if (!isVoicePlatform(conversation.platform)) {
    return null;
  }

  return {
    id: conversation.id,
    userId: conversation.userId,
    platform: conversation.platform,
    status: conversation.status,
    createdAt: conversation.createdAt,
    updatedAt: conversation.updatedAt,
    transcript: conversation.conversationLogMessages,
    actions: conversation.voiceActions,
    metadata: conversation.metadata,
  };
}
