import type { PayloadRequest } from 'payload'

/**
 * 清理 90 天前的稽核日誌
 * 此任務應該透過 cron job 定期執行（建議每天一次）
 */
export const cleanupAuditLogs = {
  slug: 'cleanup-audit-logs',
  label: '清理 90 天前的稽核日誌',
  handler: async ({ req }: { req: PayloadRequest }) => {
    try {
      // 計算 90 天前的日期
      const ninetyDaysAgo = new Date()
      ninetyDaysAgo.setDate(ninetyDaysAgo.getDate() - 90)

      // 查找 90 天前的稽核日誌
      const oldLogs = await req.payload.find({
        collection: 'audit',
        where: {
          createdAt: {
            less_than: ninetyDaysAgo.toISOString(),
          },
        },
        depth: 0,
        limit: 1000, // 每次最多處理 1000 筆
      })

      if (oldLogs.totalDocs > 0) {
        // 批量刪除舊日誌
        for (const log of oldLogs.docs) {
          await req.payload.delete({
            collection: 'audit',
            id: log.id,
          })
        }

        req.payload.logger.info(`Cleaned up ${oldLogs.totalDocs} audit logs older than 90 days`)
      }

      return {
        success: true,
        message: `Cleaned up ${oldLogs.totalDocs} audit logs older than 90 days`,
      }
    } catch (error) {
      req.payload.logger.error('Audit log cleanup failed:', error)
      return {
        success: false,
        message: 'Audit log cleanup failed',
      }
    }
  },
}
