import { factories } from '@strapi/strapi';

export default factories.createCoreController('api::blog.blog', ({ strapi }) => ({
  async find(ctx) {
    const response = await super.find(ctx);
    if (!response || !response.data) return response;

    try {
      // Query admin users to build user lookup map
      const adminUsers = await strapi.db.query('admin::user').findMany();
      const userMap = new Map<number, string>();
      const userDesigMap = new Map<number, string>();

      adminUsers.forEach((u: any) => {
        const fullName = `${u.firstname || ''} ${u.lastname || ''}`.trim() || u.username || u.email;
        userMap.set(u.id, fullName);
      });

      const blogIds = response.data.map((b: any) => b.id);
      if (blogIds.length > 0) {
        const rawBlogs = await strapi.db.query('api::blog.blog').findMany({
          where: { id: { $in: blogIds } },
          populate: ['author', 'createdBy']
        });

        const authorMap = new Map<number, string>();
        rawBlogs.forEach((rb: any) => {
          let name = rb.authorName;
          if (!name && rb.author) {
            name = userMap.get(rb.author.id) || `${rb.author.firstname || ''} ${rb.author.lastname || ''}`.trim();
          }
          if (!name && rb.createdBy) {
            name = userMap.get(rb.createdBy.id) || `${rb.createdBy.firstname || ''} ${rb.createdBy.lastname || ''}`.trim();
          }
          if (name) authorMap.set(rb.id, name);
        });

        response.data = response.data.map((b: any) => {
          const mappedAuthor = authorMap.get(b.id) || b.authorName || b.author || null;
          return {
            ...b,
            author: mappedAuthor,
            authorName: mappedAuthor
          };
        });
      }
    } catch (err) {
      console.warn('Note: Strapi blog controller find notice:', err);
    }

    return response;
  },

  async findOne(ctx) {
    const response = await super.findOne(ctx);
    if (!response || !response.data) return response;

    try {
      const b = response.data;
      const adminUsers = await strapi.db.query('admin::user').findMany();
      const userMap = new Map<number, string>();
      adminUsers.forEach((u: any) => {
        const fullName = `${u.firstname || ''} ${u.lastname || ''}`.trim() || u.username || u.email;
        userMap.set(u.id, fullName);
      });

      const rawBlog = await strapi.db.query('api::blog.blog').findOne({
        where: { id: b.id },
        populate: ['author', 'createdBy']
      });

      let name = rawBlog?.authorName;
      if (!name && rawBlog?.author) {
        name = userMap.get(rawBlog.author.id) || `${rawBlog.author.firstname || ''} ${rawBlog.author.lastname || ''}`.trim();
      }
      if (!name && rawBlog?.createdBy) {
        name = userMap.get(rawBlog.createdBy.id) || `${rawBlog.createdBy.firstname || ''} ${rawBlog.createdBy.lastname || ''}`.trim();
      }

      const mappedAuthor = name || b.authorName || b.author || null;
      response.data = {
        ...b,
        author: mappedAuthor,
        authorName: mappedAuthor
      };
    } catch (err) {
      console.warn('Note: Strapi blog controller findOne notice:', err);
    }

    return response;
  }
}));
