import type { CollectionConfig } from 'payload'

import { createAccess } from './access/create'
import { readAccess } from './access/read'
import { updateAndDeleteAccess } from './access/updateAndDelete'
import { externalUsersLogin } from './endpoints/externalUsersLogin'
import { ensureUniqueUsername } from './hooks/ensureUniqueUsername'
import { isSuperAdmin } from '@/access/isSuperAdmin'
import { setCookieBasedOnDomain } from './hooks/setCookieBasedOnDomain'
import { tenantsArrayField } from '@payloadcms/plugin-multi-tenant/fields'

export enum UserAccessLevel {
  GUEST = 0,
  CLIENT,
  TRAINER,
  TENANT_ADMIN,
  SUPER_ADMIN,
  FULL_ACCESS,
}

const defaultTenantArrayField = tenantsArrayField({
  tenantsArrayFieldName: 'tenants',
  tenantsArrayTenantFieldName: 'tenant',
  tenantsCollectionSlug: 'tenants',
  arrayFieldAccess: {},
  tenantFieldAccess: {},
  rowFields: [
    {
      name: 'roles',
      type: 'select',
      defaultValue: ['tenant-client'],
      hasMany: true,
      options: ['tenant-admin', 'tenant-client', 'tenant-instructor'],
      required: true,
    },
  ],
})


export const Users: CollectionConfig = {
  slug: 'users',
  access: {
    create: createAccess,
    delete: updateAndDeleteAccess,
    read: readAccess,
    update: updateAndDeleteAccess,
  },
  admin: {
    defaultColumns: ['name', 'email'],
    useAsTitle: 'username',
    group: 'User Data',
  },
  auth: true,
  endpoints: [externalUsersLogin],
  fields: [
    {
      admin: {
        position: 'sidebar',
      },
      name: 'roles',
      type: 'select',
      defaultValue: ['guest'],
      hasMany: true,
      options: ['full-access', 'super-admin', 'user', 'guest'],
      access: {
        update: ({ req }) => {
          return isSuperAdmin(req.user)
        },
      },
    },
    {
      name: 'username',
      type: 'text',
      hooks: {
        beforeValidate: [ensureUniqueUsername],
      },
      index: true,
    },
    {
      ...defaultTenantArrayField,
      admin: {
        ...(defaultTenantArrayField?.admin || {}),
        position: 'sidebar',
      },
    },
    {
      name: 'clients',
      type: 'join',
      collection: 'instructorClientTenantRelations',
      on: 'instructor',
      admin: {
        condition: (data) => {
          const tenantRoles = data.tenants?.flatMap((t: any) => t.roles)
          return tenantRoles.includes('tenant-instructor')
        }
      },
    }
  ],
  timestamps: true,
  hooks: {
    afterLogin: [setCookieBasedOnDomain],
  },
}
