import { Hocuspocus } from '@hocuspocus/server'
import { Database } from '@hocuspocus/extension-database'
import { verifyToken } from './auth.js'
import { fetchDocument, storeDocument } from './storage.js'

const PORT = parseInt(process.env.PORT || '4000', 10)

const server = new Hocuspocus({
  port: PORT,

  async onAuthenticate({ token, documentName }) {
    // Verify JWT from Supabase
    const user = verifyToken(token)
    if (!user) {
      throw new Error('Unauthorized')
    }

    // Extract document ID from room name (format: doc:{uuid})
    const docId = documentName.replace('doc:', '')

    // TODO: Check if user has access to this document
    // For now, any authenticated user can access any document
    // In production, check documents table + document_collaborators

    return {
      user: {
        id: user.sub,
        email: user.email,
      },
    }
  },

  extensions: [
    new Database({
      async fetch({ documentName }) {
        const docId = documentName.replace('doc:', '')
        return fetchDocument(docId)
      },

      async store({ documentName, state }) {
        const docId = documentName.replace('doc:', '')
        await storeDocument(docId, state)
      },
    }),
  ],
})

server.listen().then(() => {
  console.log(`Hocuspocus collaboration server running on port ${PORT}`)
})
