import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { kappa } from '@/services/kappa-api'
import { storage } from '@/services/storage'
import { tauriDb } from '@/services/tauri-db'
import { stripHtml } from '@/services/clean-html'
import type { KappaInitiative } from '@/types/kappa'

export const useProjectsStore = defineStore('projects', () => {
  const lastProject = storage.get('kappa_last_project')
  const projects = ref<KappaInitiative[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const selectedId = ref<number | null>(lastProject ? Number(lastProject) : null)

  const selected = computed(() =>
    projects.value.find(p => p.id === selectedId.value) ?? null
  )

  const count = computed(() => projects.value.length)

  async function fetchProjects() {
    loading.value = true
    error.value = null
    try {
      const data = await kappa.getInitiatives() as KappaInitiative[] | { results?: KappaInitiative[] }
      const raw = Array.isArray(data) ? data : (data.results ?? [])

      projects.value = raw.map(p => ({
        ...p,
        description: stripHtml(p.description || ''),
        name: p.name || p.initiative_name || `Proyecto ${p.id}`,
        initiative_name: p.initiative_name || p.name,
      }))

      await syncToTurso(projects.value)
    } catch (e: any) {
      error.value = e.message
    } finally {
      loading.value = false
    }
  }

  function toStr(v: unknown): string | null {
    if (v === null || v === undefined) return null
    return String(v)
  }

  async function syncToTurso(list: KappaInitiative[]) {
    console.log(`[Alpha] Syncing ${list.length} projects to Turso`)
    for (const p of list) {
      try {
        await tauriDb.saveProject({
          id: Number(p.id) || 0,
          name: p.initiative_name || p.name || `Proyecto ${p.id}`,
          key: toStr(p.key),
          description: toStr(p.description),
          status: toStr(p.status) || 'active',
          start_date: toStr(p.start_date),
          end_date: toStr(p.end_date),
          hus_count: null,
          epics_count: null,
        })
      } catch (e) {
        console.error(`[Alpha] Failed to save project ${p.id}:`, e)
      }
    }
  }

  function select(id: number) {
    selectedId.value = id
    storage.set('kappa_last_project', String(id))
  }

  return { projects, loading, error, selectedId, selected, count, fetchProjects, select }
})
