import Cookies from 'js-cookie'

const TokenKey = 'doctor-token'
const LegacyTokenKey = 'Admin-TokenS'

const cookieOptions = {
  expires: 1,
  sameSite: 'Strict'
}
if (process.env.NODE_ENV === 'production') {
  cookieOptions.secure = true
}

export function getToken() {
  return Cookies.get(TokenKey) || Cookies.get(LegacyTokenKey)
}

export function setToken(token) {
  return Cookies.set(TokenKey, token, cookieOptions)
}

export function removeToken() {
  Cookies.remove(TokenKey)
  Cookies.remove(LegacyTokenKey)
}


export const PermissionEnum = {
  PRESCRIBE_ADD: 'prescribe:add',       // 新增处方（西药+中药）
  PRESCRIBE_EDIT: 'prescribe:edit',     // 编辑处方
  PRESCRIBE_DELETE: 'prescribe:delete', // 删除处方
  PRESCRIBE_CREATE: 'prescribe:create'  // 开处方
};


const rolePermissions = {
  doctor: [ // 普通医生
    PermissionEnum.PRESCRIBE_ADD,
    PermissionEnum.PRESCRIBE_EDIT,
    PermissionEnum.PRESCRIBE_CREATE
  ],
  nurse: [ // 护士
    PermissionEnum.PRESCRIBE_CREATE
  ]
};


/**
 * 前端权限判断仅用于 UI 展示/按钮显隐，不可作为安全边界。
 * 敏感操作必须由后端鉴权；客户端可篡改 localStorage.userRole。
 */
export const hasPermission = (targetPermission) => {
  const userRole = localStorage.getItem('userRole');
  if (!userRole || !rolePermissions[userRole]) return false;
  return rolePermissions[userRole].includes(targetPermission);
};
