// src/server/features/notes/lib/export.service.ts
// Export service for notes to CSV format

import { db } from '@serverShared/db/client';
import { notes } from '../db/notes.table';
import { noteLayouts } from '../db/note_layouts.table';
import { isNull, eq, and } from 'drizzle-orm';
import { exportToCSV, generateExportFilename } from '@serverShared/lib/csv';
import dayjs from 'dayjs';

/**
 * Export notes to CSV format
 * @param userId - User ID for filtering notes
 * @returns Object with CSV data and filename
 */
export async function exportNotesToCSV(userId: string): Promise<{ csv: string; filename: string }> {
  // Get all notes with personal layout (including reminderAt)
  const allNotes = await db
    .select({
      id: notes.id,
      title: notes.title,
      content: notes.content,
      priority: notes.priority,
      status: notes.status,
      isPublic: notes.isPublic,
      authorId: notes.authorId,
      reminderAt: noteLayouts.reminderAt,
      column: noteLayouts.column,
      createdAt: notes.createdAt,
      updatedAt: notes.updatedAt,
    })
    .from(notes)
    .leftJoin(
      noteLayouts,
      and(
        eq(noteLayouts.noteId, notes.id),
        eq(noteLayouts.userId, userId)
      )
    )
    .where(isNull(notes.archivedAt));

  // Filter notes: own + public
  const filteredNotes = allNotes.filter(note => note.authorId === userId || note.isPublic);

  // Format data for export
  const exportData = filteredNotes.map(note => ({
    id: note.id,
    title: note.title,
    content: note.content.replace(/<[^>]*>/g, ''), // Remove HTML tags for export
    priority: getPriorityLabel(note.priority),
    status: getStatusLabel(note.status),
    isPublic: note.isPublic ? 'Да' : 'Нет',
    reminderAt: note.reminderAt ? dayjs(note.reminderAt).format('YYYY-MM-DD HH:mm') : '',
    column: note.column,
    createdAt: dayjs(note.createdAt).format('YYYY-MM-DD HH:mm:ss'),
    updatedAt: dayjs(note.updatedAt).format('YYYY-MM-DD HH:mm:ss'),
  }));

  // Define columns for export
  const columns = [
    { key: 'id', label: 'ID' },
    { key: 'title', label: 'Заголовок' },
    { key: 'content', label: 'Содержание' },
    { key: 'priority', label: 'Приоритет' },
    { key: 'status', label: 'Статус' },
    { key: 'isPublic', label: 'Публичная' },
    { key: 'reminderAt', label: 'Напоминание' },
    { key: 'column', label: 'Колонка' },
    { key: 'createdAt', label: 'Дата создания' },
    { key: 'updatedAt', label: 'Дата обновления' },
  ];

  const csv = exportToCSV(exportData, columns);
  const filename = generateExportFilename('notes');

  return { csv, filename };
}

/**
 * Get Russian label for priority
 */
export function getPriorityLabel(priority: string): string {
  const priorityMap: Record<string, string> = {
    'low': 'Низкий',
    'normal': 'Обычный',
    'high': 'Высокий',
  };
  return priorityMap[priority] || priority;
}

/**
 * Get Russian label for status
 */
export function getStatusLabel(status: string): string {
  const statusMap: Record<string, string> = {
    'active': 'Активна',
    'done': 'Выполнена',
    'cancelled': 'Отменена',
  };
  return statusMap[status] || status;
}
