import { createAccessControl } from 'better-auth/plugins/access'
import { defaultStatements, adminAc, memberAc, ownerAc } from 'better-auth/plugins/organization/access'
import { defu } from 'defu'

const customStatements = {
  application_form: ['create', 'read', 'update', 'delete', 'approve', 'reject', 'submit'],
  agreement: ['create', 'read', 'update', 'sign', 'approve', 'reject'],
  comment: ['create', 'read', 'update', 'delete'],
  document: ['create', 'read', 'update', 'delete', 'download', 'upload']
} as const

export const statement = {
  ...customStatements,
  ...defaultStatements
} as const

export const accessControl = createAccessControl(statement)

export const employerRole = accessControl.newRole(
  defu(
    {
      application_form: ['create', 'read', 'approve', 'reject'],
      agreement: ['create', 'read', 'sign', 'approve'],
      comment: ['create', 'read', 'update', 'delete'],
      document: ['create', 'read', 'update', 'delete', 'download', 'upload']
    },
    memberAc.statements
  ) as Parameters<typeof accessControl.newRole>[0]
)

export const worksCouncilMemberRole = accessControl.newRole(
  defu(
    {
      application_form: ['create', 'read', 'update', 'submit'],
      agreement: ['read', 'sign', 'approve'],
      comment: ['create', 'read', 'update', 'delete'],
      document: ['create', 'read', 'update', 'download', 'upload']
    },
    memberAc.statements
  ) as Parameters<typeof accessControl.newRole>[0]
)

export const employeeRole = accessControl.newRole(
  defu(
    {
      application_form: ['read'],
      agreement: ['read'],
      comment: ['create', 'read'],
      document: ['read', 'download']
    },
    memberAc.statements
  ) as Parameters<typeof accessControl.newRole>[0]
)

export const adminRole = accessControl.newRole(
  defu(
    {
      application_form: ['create', 'read', 'update', 'delete', 'approve', 'reject'],
      agreement: ['create', 'read', 'update', 'sign', 'approve', 'reject'],
      comment: ['create', 'read', 'update', 'delete'],
      document: ['create', 'read', 'update', 'delete', 'download', 'upload']
    },
    adminAc.statements
  ) as Parameters<typeof accessControl.newRole>[0]
)

export const ownerRole = accessControl.newRole(
  defu(
    {
      application_form: ['create', 'read', 'update', 'delete', 'approve', 'reject', 'submit'],
      agreement: ['create', 'read', 'update', 'sign', 'approve', 'reject'],
      comment: ['create', 'read', 'update', 'delete'],
      document: ['create', 'read', 'update', 'delete', 'download', 'upload']
    },
    ownerAc.statements
  ) as Parameters<typeof accessControl.newRole>[0]
)

export const ROLES = {
  EMPLOYER: 'employer',
  WORKS_COUNCIL_MEMBER: 'works_council_member',
  EMPLOYEE: 'employee',
  ADMIN: 'admin',
  OWNER: 'owner'
} as const

export type LegalRole = (typeof ROLES)[keyof typeof ROLES]
