import type { CollectionConfig } from 'payload'
import type { AfterLoginHook, AfterLogoutHook } from 'payload'

import { adminOnly } from '../../access/adminOnly'
import { authenticated } from '../../access/authenticated'
import { logLogin, logLogout } from '../../utilities/auditLogger'

const afterLogin: AfterLoginHook = async ({ req, user }) => {
  if (user?.id) {
    await logLogin(req, user.id)
  }
  return user
}

const afterLogout: AfterLogoutHook = async ({ req }) => {
  if (req.user?.id) {
    await logLogout(req, req.user.id)
  }
}

export const Users: CollectionConfig = {
  slug: 'users',
  access: {
    admin: adminOnly,
    create: adminOnly,
    delete: adminOnly,
    read: authenticated,
    update: adminOnly,
  },
  admin: {
    defaultColumns: ['name', 'email', 'role'],
    useAsTitle: 'name',
  },
  auth: true,
  hooks: {
    afterLogin: [afterLogin],
    afterLogout: [afterLogout],
  },
  fields: [
    {
      name: 'name',
      type: 'text',
    },
    {
      name: 'role',
      type: 'select',
      label: '角色',
      defaultValue: 'editor',
      required: true,
      options: [
        { label: '管理員', value: 'admin' },
        { label: '編輯者', value: 'editor' },
      ],
      admin: {
        position: 'sidebar',
      },
    },
  ],
  timestamps: true,
}
