/**
 * Миграция гостевых чатов в профиль при авторизации.
 */

import {
  clearGuestData,
  getGuestChats,
  getGuestMessages,
  hasGuestData,
} from './guest-storage';

const MIGRATION_DONE_KEY = 'gooseek_guest_migrated_at';

export async function migrateGuestToProfile(
  token: string,
  onProgress?: (current: number, total: number) => void,
): Promise<{ migrated: number; failed: number }> {
  if (!hasGuestData()) return { migrated: 0, failed: 0 };

  const chats = getGuestChats();
  let migrated = 0;
  let failed = 0;
  const total = chats.length;

  for (let i = 0; i < chats.length; i++) {
    onProgress?.(i + 1, total);
    const chat = chats[i];
    try {
      const createRes = await fetch('/api/v1/library/threads', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({
          id: chat.id,
          title: chat.title,
          sources: chat.sources,
          files: chat.files,
        }),
      });
      if (!createRes.ok) {
        failed++;
        continue;
      }

      const messages = getGuestMessages(chat.id);
      for (const msg of messages) {
        const msgRes = await fetch(
          `/api/v1/library/threads/${encodeURIComponent(chat.id)}/messages`,
          {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              Authorization: `Bearer ${token}`,
            },
            body: JSON.stringify({
              messageId: msg.messageId,
              query: msg.query,
              backendId: msg.backendId,
              responseBlocks: msg.responseBlocks,
              status: msg.status,
            }),
          },
        );
        if (!msgRes.ok) failed++;
        else migrated++;
      }
    } catch {
      failed++;
    }
  }

  clearGuestData();
  if (typeof window !== 'undefined') {
    localStorage.setItem(MIGRATION_DONE_KEY, Date.now().toString());
  }
  return { migrated, failed };
}

export function wasRecentlyMigrated(): boolean {
  if (typeof window === 'undefined') return false;
  const t = localStorage.getItem(MIGRATION_DONE_KEY);
  if (!t) return false;
  const ts = parseInt(t, 10);
  return !isNaN(ts) && Date.now() - ts < 60000;
}
