const fs = require('fs');
const axios = require('axios');

module.exports = {
  config: {
    name: "info",
    version: "5.0.0",
    description: "Lấy full info Facebook từ cookie Chrome, bao gồm avatar, cover, posts, family, likes, work, education",
    commandCategory: "Tiện ích",
    usages: "[uid/link/@tag]",
    hasPermssion: 0,
  },

  async run({ api, event, args }) {
    try {
      api.sendMessage('🔄 Đang lấy thông tin...', event.threadID, event.messageID);

      // 1️⃣ Load cookie từ appstate.json
      const cookiesJSON = JSON.parse(fs.readFileSync('appstate.json', 'utf8'));
      const cookieHeader = cookiesJSON.map(c => `${c.key}=${c.value}`).join('; ');

      // 2️⃣ UID
      const id = args[0] || event.senderID;

      // 3️⃣ Info cơ bản
      const baseFields = 'id,name,username,gender,birthday,link,about,website';
      const infoResp = await axios.get(`https://graph.facebook.com/${id}?fields=${baseFields}`, {
        headers: { cookie: cookieHeader }
      });
      const info = infoResp.data;

      // 4️⃣ Avatar + cover
      const avatarUrl = `https://graph.facebook.com/${id}/picture?width=1500&height=1500`;
      const coverUrl = info.cover?.source || null;
      const attachments = [];
      if (coverUrl) attachments.push((await axios.get(coverUrl, { responseType: 'stream' })).data);
      attachments.push((await axios.get(avatarUrl, { responseType: 'stream' })).data);

      // 5️⃣ Family
      let family = 'Không có';
      try {
        const famResp = await axios.get(`https://graph.facebook.com/${id}?fields=family`, { headers: { cookie: cookieHeader } });
        if (famResp.data.family) family = famResp.data.family.data.map(f => `${f.name} (${f.relationship})`).join('\n');
      } catch {}

      // 6️⃣ Posts (5 posts gần nhất)
      let posts = 'Không có bài đăng';
      try {
        const postsResp = await axios.get(`https://graph.facebook.com/${id}?fields=posts.limit(5){created_time,message,actions}`, { headers: { cookie: cookieHeader } });
        if (postsResp.data.posts?.data) {
          posts = postsResp.data.posts.data.map((p, i) => {
            const link = p.actions?.[0]?.link?.replace('https://www.facebook.com','https://FB.com') || '❎';
            return `${i+1}. ${p.message || 'Không có nội dung'}\n   ⏰ ${p.created_time}\n   🔗 Link: ${link}`;
          }).join('\n\n');
        }
      } catch {}

      // 7️⃣ Likes (5 likes)
      let likes = 'Không có';
      try {
        const likesResp = await axios.get(`https://graph.facebook.com/${id}?fields=likes.limit(5){name,category,id}`, { headers: { cookie: cookieHeader } });
        if (likesResp.data.likes?.data) {
          likes = likesResp.data.likes.data.map((l, i) => `${i+1}. ${l.name} (${l.category})\n   🔗 Link: FB.com/${l.id}`).join('\n');
        }
      } catch {}

      // 8️⃣ Work
      let work = 'Không có';
      try {
        const workResp = await axios.get(`https://graph.facebook.com/${id}?fields=work`, { headers: { cookie: cookieHeader } });
        if (workResp.data.work) work = workResp.data.work.map(w => `${w.employer?.name || '❎'}\n   ➛ Link: FB.com/${w.id || ''}`).join('\n');
      } catch {}

      // 9️⃣ Education
      let education = 'Không có';
      try {
        const eduResp = await axios.get(`https://graph.facebook.com/${id}?fields=education`, { headers: { cookie: cookieHeader } });
        if (eduResp.data.education) education = eduResp.data.education.map(e => `${e.school?.name || '❎'} (${e.type || '❎'})`).join('\n');
      } catch {}

      // 10️⃣ Message tổng hợp
      const message = `
╭────────────⭓
│ Tên: ${info.name}
│ Biệt danh: ${info.username || '❎'}
│ FB: ${info.link || '❎'}
│ Giới tính: ${info.gender || '❎'}
│ Sinh nhật: ${info.birthday || '❎'}
│ Giới thiệu: ${info.about || 'Không có'}
│ Website: ${info.website || 'Không có'}
├────────────⭔
│ Family: 
${family}
├────────────⭔
│ 5 Posts gần nhất:
${posts}
├────────────⭔
│ Likes (5):
${likes}
├────────────⭔
│ Work: 
${work}
├────────────⭔
│ Education:
${education}
╰────────────⭓`;

      api.sendMessage({ body: message, attachment: attachments }, event.threadID, event.messageID);

    } catch (err) {
      api.sendMessage(`❌ Lỗi: ${err.message}`, event.threadID, event.messageID);
    }
  }
};
