import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { redirect, notFound } from 'next/navigation'
import { StoryWorkspace } from '@/components/story-workspace'

interface StoryPageProps {
  params: { id: string }
}

export default async function StoryPage({ params }: StoryPageProps) {
  const session = await auth()
  if (!session?.user) redirect('/login')

  const story = await prisma.storyMaster.findUnique({
    where: { id: params.id },
    include: {
      sceneInstances: {
        where: { isActive: true },
        orderBy: { positionNumber: 'asc' },
        include: {
          catalog: true,
          scene: { select: { id: true, wordCount: true, status: true } },
        },
      },
      characters: {
        orderBy: { sortOrder: 'asc' },
      },
      seats: {
        include: { user: { select: { id: true, displayName: true, avatar: true } } },
      },
      creator: { select: { id: true, displayName: true, avatar: true } },
    },
  })

  if (!story) notFound()

  // Check access
  const hasAccess =
    story.creatorId === session.user.id ||
    story.seats.some((s) => s.userId === session.user.id) ||
    (session.user as any).role === 'admin'

  if (!hasAccess) redirect('/dashboard')

  const userSeat = story.seats.find((s) => s.userId === session.user.id)
  const userRole = story.creatorId === session.user.id
    ? 'owner'
    : userSeat?.role ?? 'viewer'

  return (
    <StoryWorkspace
      story={story}
      userRole={userRole}
      userId={session.user.id}
    />
  )
}
