'use strict'
const db = uniCloud.database()

const allowedUpdateFields = [
  'pet_id',
  'type',
  'title',
  'scheduledDate',
  'frequency',
  'interval',
  'status',
  'reminderDays',
  'relatedRecordId',
  'note'
]

exports.main = async (event, context) => {
  const { action, uid } = event

  if (!uid) {
    return { code: -1, message: '缺少用户标识' }
  }

  try {
    switch (action) {
      case 'list': {
        const { status, petId, page, pageSize } = event
        const where = { user_id: uid }
        if (status && status !== 'all') where.status = status
        if (petId) where.pet_id = petId

        const p = page || 1
        const ps = pageSize || 100
        const skip = (p - 1) * ps
        const res = await db.collection('schedules')
          .where(where)
          .orderBy('scheduledDate', 'asc')
          .skip(skip)
          .limit(ps)
          .get()

        return {
          code: 0,
          data: {
            list: res.data || [],
            total: res.affectedDocs !== undefined ? res.affectedDocs : (res.data || []).length
          }
        }
      }

      case 'detail': {
        const { scheduleId } = event
        if (!scheduleId) {
          return { code: -1, message: '缺少提醒ID' }
        }
        const res = await db.collection('schedules').doc(scheduleId).get()
        const schedule = res.data && res.data[0]
        if (!schedule || schedule.user_id !== uid) {
          return { code: -1, message: '提醒不存在' }
        }
        return { code: 0, data: schedule }
      }

      case 'add': {
        const { pet_id, type, title, scheduledDate, frequency, interval, reminderDays, relatedRecordId, note } = event
        const scheduleDate = normalizeScheduleDate(scheduledDate)
        if (!pet_id || !title || !scheduleDate) {
          return { code: -1, message: '请填写宠物、标题和日期' }
        }
        const now = Date.now()
        const scheduleData = {
          user_id: uid,
          pet_id,
          type: type || 'custom',
          title: title || '',
          scheduledDate: scheduleDate,
          frequency: frequency || 'once',
          interval: interval || 1,
          status: 'pending',
          reminderDays: Array.isArray(reminderDays) ? reminderDays : [7, 3, 1],
          relatedRecordId: relatedRecordId || '',
          note: note || '',
          createdAt: now,
          updatedAt: now
        }
        const res = await db.collection('schedules').add(scheduleData)
        return { code: 0, data: { _id: res.id }, message: '添加成功' }
      }

      case 'update': {
        const { scheduleId } = event
        if (!scheduleId) {
          return { code: -1, message: '缺少提醒ID' }
        }

        const detailRes = await db.collection('schedules').doc(scheduleId).get()
        const schedule = detailRes.data && detailRes.data[0]
        if (!schedule || schedule.user_id !== uid) {
          return { code: -1, message: '提醒不存在' }
        }

        const updateFields = {}
        allowedUpdateFields.forEach((field) => {
          if (event[field] !== undefined) updateFields[field] = event[field]
        })
        if (event.scheduledDate !== undefined) {
          const scheduleDate = normalizeScheduleDate(event.scheduledDate)
          if (!scheduleDate) {
            return { code: -1, message: '日期格式不正确' }
          }
          updateFields.scheduledDate = scheduleDate
        }
        updateFields.updatedAt = Date.now()
        await db.collection('schedules').doc(scheduleId).update(updateFields)
        return { code: 0, message: '更新成功' }
      }

      case 'delete': {
        const { scheduleId } = event
        if (!scheduleId) {
          return { code: -1, message: '缺少提醒ID' }
        }

        const detailRes = await db.collection('schedules').doc(scheduleId).get()
        const schedule = detailRes.data && detailRes.data[0]
        if (!schedule || schedule.user_id !== uid) {
          return { code: -1, message: '提醒不存在' }
        }

        await db.collection('schedules').doc(scheduleId).remove()
        return { code: 0, message: '删除成功' }
      }

      default:
        return { code: -1, message: `未知操作: ${action}` }
    }
  } catch (err) {
    console.error('scheduleManager error:', err)
    return { code: -1, message: err.message || '操作失败' }
  }
}

function normalizeScheduleDate(value) {
  if (!value) return 0
  if (typeof value === 'number') return value
  if (typeof value === 'string') {
    const match = value.match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})/)
    if (match) {
      return new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3])).getTime()
    }
  }
  const date = new Date(value)
  return Number.isNaN(date.getTime()) ? 0 : date.getTime()
}
