const designationMap: Record<string, string> = {
  'admin@cavininfotech.com': 'Superuser & Infrastructure Lead',
  'arvindh@cavininfotech.com': 'Chief AI Architect & Head of Data Engineering',
  'siddharth@cavininfotech.com': 'VP of Smart Factory & IIoT Solutions',
  'priya@cavininfotech.com': 'Lead Immersive UX & Spatial Computing Strategist',
  'vikram@cavininfotech.com': 'Senior Editor - Industrial Operations & OT Tech',
  'meera@cavininfotech.com': 'Senior Editor - Enterprise Software & Cloud',
};

export default {
  async beforeCreate(event: any) {
    const { data } = event.params;
    const ctx = strapi.requestContext?.get();
    const user = ctx?.state?.user;

    if (user) {
      if (!data.author) {
        data.author = user.id;
      }
      if (!data.authorName) {
        data.authorName = `${user.firstname || ''} ${user.lastname || ''}`.trim() || user.username || user.email;
      }
      if (!data.authorDesignation && user.email) {
        data.authorDesignation = designationMap[user.email] || `${user.firstname || ''} ${user.lastname || ''}`.trim();
      }
    }
  },

  async beforeUpdate(event: any) {
    const { data } = event.params;
    const ctx = strapi.requestContext?.get();
    const user = ctx?.state?.user;

    if (user && data) {
      if (!data.author) {
        data.author = user.id;
      }
      if (!data.authorName && user) {
        data.authorName = `${user.firstname || ''} ${user.lastname || ''}`.trim() || user.username || user.email;
      }
      if (!data.authorDesignation && user.email) {
        data.authorDesignation = designationMap[user.email] || `${user.firstname || ''} ${user.lastname || ''}`.trim();
      }

      const isEditor = user.roles?.some((r: any) => r.code === 'strapi-editor' || r.code === 'strapi-super-admin');
      if (isEditor) {
        if (!data.editor) {
          data.editor = user.id;
        }
        if (!data.editorName && user) {
          data.editorName = `${user.firstname || ''} ${user.lastname || ''}`.trim() || user.username;
        }
        if (!data.editorDesignation && user.email) {
          data.editorDesignation = designationMap[user.email] || 'Senior Editor';
        }
      }
    }
  },
};
