import { save } from '@tauri-apps/plugin-dialog'
import { invoke } from '@tauri-apps/api/core'

function escapeCSV(val: string): string {
  if (val.includes(',') || val.includes('"') || val.includes('\n')) {
    return '"' + val.replace(/"/g, '""') + '"'
  }
  return val
}

function toCSVRow(values: string[]): string {
  return values.map(escapeCSV).join(',')
}

export function entriesToCSV(
  entries: { id?: number; start_time: string; duration: number; description?: string; billable?: number; project_id: number; task_id?: number }[],
  getProjectName: (id: number) => string,
  getClientName: (projectId: number) => string,
  getTaskName: (id?: number) => string,
  getTagNames: (entryId: number) => string
): string {
  const headers = ['Date', 'Project', 'Client', 'Task', 'Description', 'Duration (hours)', 'Billable', 'Tags']
  const rows = entries.map(e => toCSVRow([
    e.start_time.split('T')[0],
    getProjectName(e.project_id),
    getClientName(e.project_id),
    getTaskName(e.task_id),
    e.description || '',
    (e.duration / 3600).toFixed(2),
    e.billable === 1 ? 'Yes' : 'No',
    getTagNames(e.id || 0),
  ]))
  return [toCSVRow(headers), ...rows].join('\n')
}

export async function downloadCSV(content: string, defaultName: string): Promise<boolean> {
  const path = await save({
    defaultPath: defaultName,
    filters: [{ name: 'CSV', extensions: ['csv'] }],
  })
  if (!path) return false
  await invoke('save_binary_file', { path, data: Array.from(new TextEncoder().encode(content)) })
  return true
}
