import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
  db, startScheduler, stopScheduler, onScheduledTask,
  computeNextRun, DEFAULT_RULES,
  type ScheduleRule, type ScheduleAction, type ExecutionLog,
} from '@/services/scheduler'

export const useSchedulerStore = defineStore('scheduler', () => {
  const rules = ref<ScheduleRule[]>([])
  const logs = ref<ExecutionLog[]>([])
  const notifications = ref<{ id: number; ruleId: number; message: string; time: string }[]>([])
  const running = ref(false)

  const enabledRules = computed(() => rules.value.filter(r => r.enabled))
  const nextRuns = computed(() => {
    return rules.value.map(r => ({
      ...r,
      nextRun: computeNextRun(r),
    }))
  })

  async function loadRules() {
    rules.value = await db.rules.toArray()
  }

  async function loadLogs(limit = 50) {
    logs.value = await db.logs.orderBy('executedAt').reverse().limit(limit).toArray()
  }

  async function seedDefaults() {
    const existing = await db.rules.count()
    if (existing > 0) return
    const now = new Date().toISOString()
    for (const def of DEFAULT_RULES) {
      await db.rules.add({ ...def, createdAt: now, lastRun: null } as ScheduleRule)
    }
    await loadRules()
  }

  async function addRule(rule: Omit<ScheduleRule, 'id' | 'createdAt' | 'lastRun'>) {
    await db.rules.add({
      ...rule,
      createdAt: new Date().toISOString(),
      lastRun: null,
    } as ScheduleRule)
    await loadRules()
  }

  async function updateRule(id: number, changes: Partial<ScheduleRule>) {
    await db.rules.update(id, changes)
    await loadRules()
  }

  async function toggleRule(id: number) {
    const rule = rules.value.find(r => r.id === id)
    if (rule) {
      await db.rules.update(id, { enabled: !rule.enabled })
      await loadRules()
    }
  }

  async function deleteRule(id: number) {
    await db.rules.delete(id)
    await loadRules()
  }

  function start() {
    startScheduler()
    running.value = true

    onScheduledTask((ruleId, message) => {
      notifications.value.unshift({
        id: Date.now(),
        ruleId,
        message,
        time: new Date().toLocaleTimeString(),
      })
      loadLogs()
      // Mantener solo últimas 20 notificaciones
      if (notifications.value.length > 20) {
        notifications.value = notifications.value.slice(0, 20)
      }
    })
  }

  function stop() {
    stopScheduler()
    running.value = false
  }

  function dismissNotification(id: number) {
    notifications.value = notifications.value.filter(n => n.id !== id)
  }

  return {
    rules, logs, notifications, running, enabledRules, nextRuns,
    loadRules, loadLogs, seedDefaults, addRule, updateRule,
    toggleRule, deleteRule, start, stop, dismissNotification,
  }
})
