/**
 * Локальное хранение чатов гостей (localStorage).
 * При авторизации данные мигрируют в library-svc.
 */

import type { Block } from './types';

const KEY = 'gooseek_guest_data';

export interface GuestChat {
  id: string;
  title: string;
  createdAt: string;
  sources: string[];
  files: { fileId: string; name: string }[];
}

export interface GuestMessage {
  messageId: string;
  chatId: string;
  backendId: string;
  query: string;
  createdAt: string;
  responseBlocks: Block[];
  status: 'answering' | 'completed' | 'error';
}

interface GuestData {
  threads: GuestChat[];
  messages: Record<string, GuestMessage[]>;
}

function load(): GuestData {
  if (typeof window === 'undefined') {
    return { threads: [], messages: {} };
  }
  try {
    const raw = localStorage.getItem(KEY);
    if (!raw) return { threads: [], messages: {} };
    const parsed = JSON.parse(raw) as GuestData;
    return {
      threads: Array.isArray(parsed.threads) ? parsed.threads : [],
      messages: parsed.messages && typeof parsed.messages === 'object' ? parsed.messages : {},
    };
  } catch {
    return { threads: [], messages: {} };
  }
}

function save(data: GuestData): void {
  if (typeof window === 'undefined') return;
  try {
    localStorage.setItem(KEY, JSON.stringify(data));
  } catch (e) {
    console.error('[guest-storage] save failed:', e);
  }
}

export function getGuestChats(): GuestChat[] {
  const data = load();
  return [...data.threads].sort(
    (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
  );
}

export function getGuestChat(id: string): GuestChat | null {
  const data = load();
  return data.threads.find((t) => t.id === id) ?? null;
}

export function getGuestMessages(chatId: string): GuestMessage[] {
  const data = load();
  return (data.messages[chatId] ?? []).sort(
    (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
  );
}

export function upsertGuestThread(chat: {
  id: string;
  title: string;
  sources?: string[];
  files?: { fileId: string; name: string }[];
}): void {
  const data = load();
  const existing = data.threads.findIndex((t) => t.id === chat.id);
  const now = new Date().toISOString();
  const thread: GuestChat = {
    id: chat.id,
    title: chat.title,
    createdAt: existing >= 0 ? data.threads[existing].createdAt : now,
    sources: chat.sources ?? [],
    files: chat.files ?? [],
  };
  if (existing >= 0) {
    data.threads[existing] = { ...data.threads[existing], ...thread };
  } else {
    data.threads.push(thread);
  }
  save(data);
}

export function upsertGuestMessage(
  chatId: string,
  message: {
    messageId: string;
    query: string;
    backendId?: string;
    responseBlocks?: Block[];
    status?: 'answering' | 'completed' | 'error';
  },
): void {
  const data = load();
  if (!data.messages[chatId]) data.messages[chatId] = [];
  const idx = data.messages[chatId].findIndex((m) => m.messageId === message.messageId);
  const now = new Date().toISOString();
  const msg: GuestMessage = {
    messageId: message.messageId,
    chatId,
    backendId: message.backendId ?? '',
    query: message.query,
    createdAt: idx >= 0 ? data.messages[chatId][idx].createdAt : now,
    responseBlocks: message.responseBlocks ?? [],
    status: message.status ?? 'answering',
  };
  if (idx >= 0) {
    data.messages[chatId][idx] = msg;
  } else {
    data.messages[chatId].push(msg);
  }
  save(data);
}

export function setGuestMessages(
  chatId: string,
  messages: Omit<GuestMessage, 'chatId'>[],
): void {
  const data = load();
  data.messages[chatId] = messages.map((m) => ({
    ...m,
    chatId,
  }));
  save(data);
}

export function deleteGuestChat(chatId: string): void {
  const data = load();
  data.threads = data.threads.filter((t) => t.id !== chatId);
  delete data.messages[chatId];
  save(data);
}

export function clearGuestData(): void {
  if (typeof window === 'undefined') return;
  localStorage.removeItem(KEY);
}

export function hasGuestData(): boolean {
  const data = load();
  return data.threads.length > 0;
}
