import * as Y from 'yjs'
import { supabase } from '../auth/supabase.ts'

const MIGRATED_KEY = 'calctext-migrated-to-cloud'

interface LegacyDoc {
  id: string
  title: string
  content: string
  folderId: string | null
  isFavorite: boolean
  createdAt: string
  updatedAt: string
}

/**
 * Migrate documents from localStorage to Supabase + IndexedDB.
 * Only runs once per user. Idempotent.
 */
export async function migrateLegacyDocuments(userId: string): Promise<number> {
  if (!supabase) return 0

  // Check if already migrated
  const migratedFlag = localStorage.getItem(MIGRATED_KEY)
  if (migratedFlag === userId) return 0

  // Read legacy documents from localStorage
  let legacyDocs: LegacyDoc[] = []
  try {
    const raw = localStorage.getItem('calctext-documents')
    if (raw) legacyDocs = JSON.parse(raw)
  } catch {
    return 0
  }

  if (legacyDocs.length === 0) {
    localStorage.setItem(MIGRATED_KEY, userId)
    return 0
  }

  // Upload each document to Supabase
  let migrated = 0
  for (const doc of legacyDocs) {
    try {
      // Create document metadata in Supabase
      const { data: cloudDoc, error: docError } = await supabase
        .from('documents')
        .insert({
          owner_id: userId,
          title: doc.title,
          folder_id: null, // Folders migrated separately if needed
          is_favorite: doc.isFavorite,
          created_at: doc.createdAt,
          updated_at: doc.updatedAt,
        })
        .select('id')
        .single()

      if (docError || !cloudDoc) {
        console.error('Failed to migrate doc:', doc.title, docError)
        continue
      }

      // Create Y.Doc with the document content
      const ydoc = new Y.Doc()
      const ytext = ydoc.getText('content')
      ytext.insert(0, doc.content)
      const state = Y.encodeStateAsUpdate(ydoc)

      // Store Y.Doc snapshot
      await supabase
        .from('ydoc_snapshots')
        .upsert({
          document_id: cloudDoc.id,
          state: Array.from(state), // Store as integer array (JSON-compatible)
          updated_at: new Date().toISOString(),
        })

      ydoc.destroy()
      migrated++
    } catch (err) {
      console.error('Migration error for doc:', doc.title, err)
    }
  }

  // Mark migration complete
  localStorage.setItem(MIGRATED_KEY, userId)

  return migrated
}
