import { useCallback } from 'react'
import { nanoid } from 'nanoid'
import { supabase } from '../auth/supabase.ts'

export type SharePermission = 'view' | 'edit'

interface ShareInfo {
  token: string
  permission: SharePermission
  url: string
}

/**
 * Hook for managing document share tokens.
 */
export function useShareToken() {
  /** Generate a share link for a document */
  const createShareLink = useCallback(async (
    documentId: string,
    permission: SharePermission = 'view',
  ): Promise<ShareInfo | null> => {
    if (!supabase) return null

    const token = nanoid(21)
    const { error } = await supabase
      .from('documents')
      .update({
        share_token: token,
        share_permission: permission,
      })
      .eq('id', documentId)

    if (error) {
      console.error('Failed to create share link:', error)
      return null
    }

    const url = `${window.location.origin}/s/${token}`
    return { token, permission, url }
  }, [])

  /** Revoke a share link */
  const revokeShareLink = useCallback(async (documentId: string): Promise<void> => {
    if (!supabase) return

    await supabase
      .from('documents')
      .update({
        share_token: null,
        share_permission: null,
      })
      .eq('id', documentId)
  }, [])

  /** Resolve a share token to document info */
  const resolveShareToken = useCallback(async (token: string) => {
    if (!supabase) return null

    const { data, error } = await supabase
      .from('documents')
      .select('id, title, share_permission, owner_id')
      .eq('share_token', token)
      .single()

    if (error || !data) return null
    return data
  }, [])

  return { createShareLink, revokeShareLink, resolveShareToken }
}
