import { invoke as tauriInvoke } from '@tauri-apps/api/core'
import db from '@/services/db'

const _invoke = typeof tauriInvoke === 'function' ? tauriInvoke : undefined

function safeInvoke<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {
  if (!_invoke) {
    return fallbackInvoke<T>(cmd, args)
  }
  return _invoke(cmd, args)
}

/**
 * Cuando Tauri no está disponible, algunas operaciones se pueden
 * redirigir a Dexie (IndexedDB) para mantener funcionalidad en bun dev.
 */
async function fallbackInvoke<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {
  switch (cmd) {
    // ─── HuDrafts → Dexie ─────────────────────────────
    case 'get_hu_drafts': {
      const { getDrafts } = await import('@/services/hu-drafts-db')
      const pid = (args as any)?.initiativeId
      const drafts = pid ? await getDrafts(Number(pid)) : await getDrafts(0)
      return drafts as unknown as T
    }
    case 'save_hu_draft': {
      const { saveDraft } = await import('@/services/hu-drafts-db')
      const draft = (args as any)?.draft
      if (draft) await saveDraft({ id: draft.id, projectId: draft.initiative_id || 0, title: draft.title, description: draft.description || '', acceptanceCriteria: draft.acceptance_criteria || '', priority: 'Media', type: draft.item_type || 'U', metadata: '{}', syncStatus: draft.sync_status || 'draft', createdAt: new Date().toISOString() })
      return null as unknown as T
    }
    case 'delete_hu_draft': {
      const { deleteDraft } = await import('@/services/hu-drafts-db')
      await deleteDraft(String((args as any)?.id))
      return null as unknown as T
    }
    // ─── Users → Dexie ────────────────────────────────
    case 'get_users': {
      try { const r = await (db as any).table('alpha_users').toArray(); return r as unknown as T } catch { return [] as unknown as T }
    }
    case 'save_user': {
      const u = (args as any)?.user
      if (u) try { await (db as any).table('alpha_users').put(u) } catch {}
      return null as unknown as T
    }
    // ─── User Stories → Dexie ──────────────────────────
    case 'get_user_stories': {
      const initiativeId = (args as any)?.initiativeId
      try {
        const all = await (db as any).table('user_stories').toArray()
        return (initiativeId ? all.filter((r: any) => r.initiative_id === initiativeId) : all) as unknown as T
      } catch { return [] as unknown as T }
    }
    case 'save_user_story': {
      const s = (args as any)?.story
      if (s) try { await (db as any).table('user_stories').put(s) } catch {}
      return null as unknown as T
    }
    // ─── Por defecto: no hay fallback ─────────────────
    default:
      return null as unknown as T
  }
}

export interface ProjectRecord {
  id: number
  name: string
  key: string | null
  description: string | null
  status: string
  start_date: string | null
  end_date: string | null
  hus_count: number | null
  epics_count: number | null
}

export interface EpicRecord {
  id: number
  initiative_id: number
  code: string | null
  name: string
  description: string | null
  status: string | null
  client_taker: number | null
  stimated_start_date: string | null
  stimated_end_date: string | null
  start_date: string | null
  end_date: string | null
  created_at: string | null
  updated_at: string | null
}

export interface UserStoryRecord {
  id: number
  initiative_id: number
  epic_id: number | null
  code: string | null
  title: string
  description: string | null
  acceptance_criteria: string | null
  status: string | null
  priority: string | null
  story_points: number | null
  estimated_hours: number | null
  actual_hours: number | null
  assigned_to: number | null
  sprint: string | null
  has_impairment: boolean
  item_type: string | null
  hierarchy_path: string | null
  parent_code: string | null
  created_at: string | null
}

export interface ImpairmentRecord {
  id: number
  hu_id: number
  responsible: string | null
  pending_activity: string | null
  pending_type: string | null
  type_impediment: boolean
  delivery_date: string | null
  status: boolean
  created_at: string | null
  updated_at: string | null
}

export interface HuDraftRecord {
  id: string
  initiative_id: number | null
  code: string | null
  title: string
  description: string | null
  acceptance_criteria: string | null
  item_type: string | null
  hierarchy_path: string | null
  story_points: number | null
  sprint: string | null
  assigned_to: string | null
  sync_status: string
  kappa_id: number | null
  created_at: string | null
  updated_at: string | null
}

export interface ProjectMemberRecord {
  id: number
  user_id: number
  initiative_id: number
  initiative_name: string | null
  role: string | null
  assigned_at: string | null
}

export interface AbsenceRecord {
  id: number
  user_id: number
  start_date: string
  end_date: string
  type: string
  reason: string | null
  created_at: string | null
}

export interface DailyLogRecord {
  id: number
  user_id: number
  initiative_id: number
  date: string
  work_item_id: number | null
  what_worked_on: string | null
  progress_pct: number | null
  impediments: string | null
  plan_for_tomorrow: string | null
  hours_spent: number | null
  created_at: string | null
}

export interface PerformanceRecord {
  id: number
  user_id: number
  initiative_id: number | null
  period: string
  planned_sp: number | null
  completed_sp: number | null
  planned_hours: number | null
  actual_hours: number | null
  velocity: number | null
  spi: number | null
  cpi: number | null
  compliance_pct: number | null
  impediment_count: number | null
  calculated_at: string | null
}

export interface WorkItemRecord {
  id: number
  project_id: number
  code: string | null
  title: string
  description: string | null
  type: string
  status: string
  priority: string
}

export interface AlphaUserRecord {
  id: number
  email: string
  first_name: string
  last_name: string
  role: string | null
  seniority: string | null
  cell_id: number | null
  is_active: boolean
  created_at: string | null
}

export interface CellRecord {
  id: number
  name: string
  description: string | null
  created_at: string | null
}

export const tauriDb = {
  // Projects
  getProjects(): Promise<ProjectRecord[]> {
    return safeInvoke('get_projects')
  },
  saveProject(project: ProjectRecord): Promise<number> {
    return safeInvoke('save_project', { project })
  },
  updateProjectCounts(initiativeId: number): Promise<void> {
    return safeInvoke('update_project_counts', { initiativeId })
  },
  deleteProject(id: number): Promise<void> {
    return safeInvoke('delete_project', { id })
  },

  // Work Items
  getWorkItems(projectId: number): Promise<WorkItemRecord[]> {
    return safeInvoke('get_work_items', { projectId })
  },
  saveWorkItem(item: WorkItemRecord): Promise<number> {
    return safeInvoke('save_work_item', { item })
  },
  deleteWorkItem(id: number): Promise<void> {
    return safeInvoke('delete_work_item', { id })
  },

  // Epics
  getEpics(initiativeId: number): Promise<EpicRecord[]> {
    return safeInvoke('get_epics', { initiativeId })
  },
  saveEpic(epic: EpicRecord): Promise<number> {
    return safeInvoke('save_epic', { epic })
  },
  deleteEpic(id: number): Promise<void> {
    return safeInvoke('delete_epic', { id })
  },

  // User Stories
  getUserStories(initiativeId: number, epicId?: number): Promise<UserStoryRecord[]> {
    return safeInvoke('get_user_stories', { initiativeId, epicId: epicId ?? null })
  },
  saveUserStory(story: UserStoryRecord): Promise<number> {
    return safeInvoke('save_user_story', { story })
  },
  deleteUserStory(id: number): Promise<void> {
    return safeInvoke('delete_user_story', { id })
  },

  // Users
  getUsers(): Promise<AlphaUserRecord[]> {
    return safeInvoke('get_users')
  },
  saveUser(user: AlphaUserRecord): Promise<number> {
    return safeInvoke('save_user', { user })
  },
  updateUserFields(id: number, role: string | null, seniority: string | null, cell_id: number | null): Promise<void> {
    return safeInvoke('update_user_fields', { id, role, seniority, cellId: cell_id })
  },

  // Cells
  getCells(): Promise<CellRecord[]> {
    return safeInvoke('get_cells')
  },
  saveCell(cell: CellRecord): Promise<number> {
    return safeInvoke('save_cell', { cell })
  },

  // Project Members
  getProjectMembers(userId: number): Promise<ProjectMemberRecord[]> {
    return safeInvoke('get_project_members', { userId })
  },
  saveProjectMembers(userId: number, members: ProjectMemberRecord[]): Promise<void> {
    return safeInvoke('save_project_members', { userId, members })
  },

  // Absences
  getAbsences(userId: number): Promise<AbsenceRecord[]> {
    return safeInvoke('get_absences', { userId })
  },
  saveAbsence(absence: AbsenceRecord): Promise<number> {
    return safeInvoke('save_absence', { absence })
  },
  deleteAbsence(id: number): Promise<void> {
    return safeInvoke('delete_absence', { id })
  },

  // Daily Logs
  getDailyLogs(userId: number, initiativeId?: number): Promise<DailyLogRecord[]> {
    return safeInvoke('get_daily_logs', { userId, initiativeId: initiativeId ?? null })
  },
  saveDailyLog(log: DailyLogRecord): Promise<number> {
    return safeInvoke('save_daily_log', { log })
  },

  // Performance
  getPerformance(userId: number, initiativeId?: number): Promise<PerformanceRecord[]> {
    return safeInvoke('get_performance', { userId, initiativeId })
  },
  savePerformance(snap: PerformanceRecord): Promise<number> {
    return safeInvoke('save_performance', { snap })
  },

  // Impairments
  getImpairments(huId: number): Promise<ImpairmentRecord[]> {
    return safeInvoke('get_impairments', { huId })
  },
  saveImpairment(imp: ImpairmentRecord): Promise<number> {
    return safeInvoke('save_impairment', { imp })
  },
  deleteImpairment(id: number): Promise<void> {
    return safeInvoke('delete_impairment', { id })
  },

  // HU Drafts
  getHuDrafts(initiativeId?: number): Promise<HuDraftRecord[]> {
    return safeInvoke('get_hu_drafts', { initiativeId: initiativeId ?? null })
  },
  saveHuDraft(draft: HuDraftRecord): Promise<void> {
    return safeInvoke('save_hu_draft', { draft })
  },
  deleteHuDraft(id: string): Promise<void> {
    return safeInvoke('delete_hu_draft', { id })
  },
}
