import * as XLSX from 'xlsx'
import { kappa } from '@/services/kappa-api'
import { storage } from '@/services/storage'
import type { HuDraftRecord } from '@/services/tauri-db'

const BASE = '/api'

async function uploadExcel(initiativeId: number, file: Blob): Promise<Response> {
  const token = storage.get('kappa_token')
  const formData = new FormData()
  formData.append('file', file, 'HistoriasUsuario.xlsx')
  return fetch(`${BASE}/userstorys/upload-excel/${initiativeId}/`, {
    method: 'POST',
    headers: token ? { 'Authorization': `Bearer ${token}` } : {},
    body: formData,
  })
}

export async function pushDraftsToKappa(drafts: HuDraftRecord[], initiativeId: number): Promise<{ ok: number; fail: number }> {
  const wb = XLSX.utils.book_new()

  const rows = drafts.map(d => ({
    Titulo: d.hierarchy_path ? `[${d.hierarchy_path}] ${d.title}` : d.title,
    Descripción: d.description || '',
    'Story points': d.story_points ?? '',
    Prioridad: null,
    Asignado_a: d.assigned_to ?? null,
    'Criterios aceptación': d.acceptance_criteria || '',
  }))

  const ws = XLSX.utils.json_to_sheet(rows)
  XLSX.utils.book_append_sheet(wb, ws, 'HistoriasUsuario')

  const wbOut = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
  const blob = new Blob([wbOut], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })

  try {
    const resp = await uploadExcel(initiativeId, blob)
    if (resp.ok) {
      return { ok: drafts.length, fail: 0 }
    }
    const text = await resp.text()
    console.error('[Alpha] Upload failed:', resp.status, text)
    return { ok: 0, fail: drafts.length }
  } catch (e) {
    console.error('[Alpha] Upload error:', e)
    return { ok: 0, fail: drafts.length }
  }
}
