import { mockReminders } from '../mock-data/reminders'
import type { Reminder, ReminderActivity } from '../domain/reminder'
import { ReminderStatus } from '../domain/reminder'
import type { IReminderProvider } from './IReminderProvider'

let store: Reminder[] = [...mockReminders]

function now(): string {
  return new Date().toISOString()
}

function addActivity(reminder: Reminder, entry: ReminderActivity): Reminder {
  return { ...reminder, activity: [...reminder.activity, entry], updatedAt: now() }
}

export const MockupReminderProvider: IReminderProvider = {
  async getAll() {
    return [...store]
  },

  async getById(id) {
    return store.find(r => r.id === id) ?? null
  },

  async update(id, data) {
    const idx = store.findIndex(r => r.id === id)
    if (idx === -1) throw new Error(`Reminder ${id} not found`)
    store[idx] = { ...store[idx], ...data, updatedAt: now() }
    return store[idx]
  },

  async complete(id, note) {
    const idx = store.findIndex(r => r.id === id)
    if (idx === -1) throw new Error(`Reminder ${id} not found`)
    store[idx] = addActivity(
      { ...store[idx], status: ReminderStatus.COMPLETED },
      { at: now(), by: 'current-user', action: 'COMPLETED', note },
    )
    return store[idx]
  },

  async dismiss(id, note) {
    const idx = store.findIndex(r => r.id === id)
    if (idx === -1) throw new Error(`Reminder ${id} not found`)
    store[idx] = addActivity(
      { ...store[idx], status: ReminderStatus.DISMISSED },
      { at: now(), by: 'current-user', action: 'DISMISSED', note },
    )
    return store[idx]
  },

  async snooze(id, until) {
    const idx = store.findIndex(r => r.id === id)
    if (idx === -1) throw new Error(`Reminder ${id} not found`)
    store[idx] = addActivity(
      { ...store[idx], status: ReminderStatus.SNOOZED, snoozedUntil: until },
      { at: now(), by: 'current-user', action: 'SNOOZED', note: `Snoozed until ${until}` },
    )
    return store[idx]
  },

  async create(data) {
    const reminder: Reminder = {
      ...data,
      id: crypto.randomUUID(),
      activity: [{ at: now(), by: 'current-user', action: 'CREATED' }],
      createdAt: now(),
      updatedAt: now(),
    }
    store.push(reminder)
    return reminder
  },
}
