import { ref, computed } from 'vue'
import { useSettings } from './useSettings.js'

const DEFAULT_REMINDER_DAYS = 7

const lastBackupAt = ref(null)
const dbCreatedAt = ref(null)
const backupReminderDays = ref(DEFAULT_REMINDER_DAYS)
const sessionReminderShown = ref(false)

export function useBackupStatus() {
  const { get, set } = useSettings()

  async function load() {
    const lastBackupAtStr = await get('last_backup_at')
    if (lastBackupAtStr) {
      lastBackupAt.value = new Date(lastBackupAtStr)
    } else {
      lastBackupAt.value = null
    }

    const dbCreatedAtStr = await get('db_created_at')
    if (dbCreatedAtStr) {
      dbCreatedAt.value = new Date(dbCreatedAtStr)
    } else {
      dbCreatedAt.value = null
    }

    const daysStr = await get('backup_reminder_days')
    const parsed = parseInt(daysStr, 10)
    if (!isNaN(parsed) && parsed >= 1 && parsed <= 365) {
      backupReminderDays.value = parsed
    } else {
      if (daysStr !== null && daysStr !== undefined) {
        console.warn(
          `[useBackupStatus] Invalid backup_reminder_days value: "${daysStr}", falling back to ${DEFAULT_REMINDER_DAYS}`,
        )
      }
      backupReminderDays.value = DEFAULT_REMINDER_DAYS
    }
  }

  const daysSinceBackup = computed(() => {
    const effectiveDate = lastBackupAt.value || dbCreatedAt.value
    if (!effectiveDate) return null
    const now = new Date()
    const diffMs = now.getTime() - effectiveDate.getTime()
    return Math.floor(diffMs / (1000 * 60 * 60 * 24))
  })

  const isStale = computed(() => {
    const effectiveDate = lastBackupAt.value || dbCreatedAt.value
    if (!effectiveDate) return true
    const now = new Date()
    const diffMs = now.getTime() - effectiveDate.getTime()
    const thresholdMs = backupReminderDays.value * 86_400_000
    return diffMs > thresholdMs
  })

  const visible = computed(() => {
    return isStale.value
  })

  async function markBackedUp() {
    const now = new Date().toISOString()
    await set('last_backup_at', now)
    lastBackupAt.value = new Date(now)
  }

  return {
    lastBackupAt,
    dbCreatedAt,
    daysSinceBackup,
    isStale,
    visible,
    load,
    markBackedUp,
    backupReminderDays,
    sessionReminderShown,
  }
}
