/**
 * library-svc client — сохранение threads и messages вместо SQLite
 */

const LIBRARY_SVC_URL = process.env.LIBRARY_SVC_URL ?? '';

export interface Block {
  type: string;
  id?: string;
  data?: unknown;
}

export class LibraryClient {
  constructor(
    private baseUrl: string,
    private authHeader: string | undefined,
  ) {}

  get enabled(): boolean {
    return !!this.baseUrl && !!this.authHeader;
  }

  async upsertMessage(
    threadId: string,
    messageId: string,
    query: string,
    opts: {
      backendId?: string;
      responseBlocks?: Block[];
      status?: string;
      sources?: string[];
      files?: { fileId: string; name: string }[];
    } = {},
  ): Promise<void> {
    if (!this.enabled) return;
    try {
      const res = await fetch(
        `${this.baseUrl.replace(/\/$/, '')}/api/v1/library/threads/${encodeURIComponent(threadId)}/messages`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: this.authHeader!,
          },
          body: JSON.stringify({
            messageId,
            query,
            backendId: opts.backendId ?? '',
            responseBlocks: opts.responseBlocks ?? [],
            status: opts.status ?? 'answering',
            sources: opts.sources ?? [],
            files: opts.files ?? [],
          }),
          signal: AbortSignal.timeout(5000),
        },
      );
      if (!res.ok) {
        const err = await res.text();
        console.error('[LibraryClient] upsertMessage failed:', res.status, err);
      }
    } catch (err) {
      console.error('[LibraryClient] upsertMessage error:', err);
    }
  }

  async updateMessage(
    threadId: string,
    messageId: string,
    opts: { responseBlocks?: Block[]; status?: string },
  ): Promise<void> {
    if (!this.enabled) return;
    try {
      const res = await fetch(
        `${this.baseUrl.replace(/\/$/, '')}/api/v1/library/threads/${encodeURIComponent(threadId)}/messages/${encodeURIComponent(messageId)}`,
        {
          method: 'PATCH',
          headers: {
            'Content-Type': 'application/json',
            Authorization: this.authHeader!,
          },
          body: JSON.stringify(opts),
          signal: AbortSignal.timeout(5000),
        },
      );
      if (!res.ok) {
        const err = await res.text();
        console.error('[LibraryClient] updateMessage failed:', res.status, err);
      }
    } catch (err) {
      console.error('[LibraryClient] updateMessage error:', err);
    }
  }

  static create(authHeader: string | undefined): LibraryClient {
    return new LibraryClient(LIBRARY_SVC_URL, authHeader);
  }
}
