import type { CollectionConfig } from 'payload'

import { adminOnly } from '../../access/adminOnly'

export const Audit: CollectionConfig = {
  slug: 'audit',
  access: {
    create: () => false, // 僅透過程式自動創建
    delete: adminOnly,
    read: adminOnly,
    update: () => false, // 不允許修改日誌
  },
  admin: {
    defaultColumns: ['timestamp', 'action', 'collection', 'userId'],
    useAsTitle: 'action',
    description: '系統稽核日誌 - 自動記錄所有重要操作',
  },
  fields: [
    {
      name: 'action',
      type: 'select',
      required: true,
      options: [
        { label: '登入', value: 'login' },
        { label: '登出', value: 'logout' },
        { label: '創建', value: 'create' },
        { label: '更新', value: 'update' },
        { label: '刪除', value: 'delete' },
        { label: '發布', value: 'publish' },
        { label: '取消發布', value: 'unpublish' },
      ],
    },
    {
      name: 'collection',
      type: 'text',
      required: true,
      admin: {
        description: '受影響的集合名稱',
      },
    },
    {
      name: 'documentId',
      type: 'text',
      admin: {
        description: '受影響的文件 ID',
      },
    },
    {
      name: 'documentTitle',
      type: 'text',
      admin: {
        description: '受影響的文件標題',
      },
    },
    {
      name: 'userId',
      type: 'text',
      required: true,
      admin: {
        description: '執行操作的使用者 ID',
      },
    },
    {
      name: 'userName',
      type: 'text',
      admin: {
        description: '執行操作的使用者名稱',
      },
    },
    {
      name: 'userEmail',
      type: 'text',
      admin: {
        description: '執行操作的使用者信箱',
      },
    },
    {
      name: 'userRole',
      type: 'select',
      options: [
        { label: '管理員', value: 'admin' },
        { label: '編輯者', value: 'editor' },
      ],
    },
    {
      name: 'ipAddress',
      type: 'text',
      admin: {
        description: 'IP 位址',
      },
    },
    {
      name: 'userAgent',
      type: 'text',
      admin: {
        description: '瀏覽器 User Agent',
      },
    },
    {
      name: 'changes',
      type: 'json',
      admin: {
        description: '變更內容詳細資訊',
      },
    },
  ],
  timestamps: true,
}
