import { PrismaClient } from '@prisma/client';
import * as bcrypt from 'bcryptjs';

const prisma = new PrismaClient();

// ─── Demo data ────────────────────────────────────────────────────────────────

const DEMO_USERS = [
  { name: 'Super Admin',     email: 'admin@haveyoursay.in',  phone: null,          role: 'SUPER_ADMIN',    status: 'APPROVED',  membership: 'PREMIUM', password: 'Admin@123' },
  { name: 'Arjun Moderator', email: 'arjun@haveyoursay.in',  phone: null,          role: 'MODERATOR',      status: 'APPROVED',  membership: 'PREMIUM', password: 'Mod@1234' },
  { name: 'Priya Sharma',    email: 'priya.sharma@gmail.com', phone: '+919876543210', role: 'PREMIUM_MEMBER', status: 'APPROVED',  membership: 'PREMIUM' },
  { name: 'Rahul Verma',     email: 'rahul.v@outlook.com',   phone: '+919765432101', role: 'PREMIUM_MEMBER', status: 'APPROVED',  membership: 'VIP'     },
  { name: 'Sneha Patel',     email: 'sneha.p@gmail.com',     phone: '+919654321012', role: 'FREE_MEMBER',    status: 'APPROVED',  membership: 'FREE'    },
  { name: 'Vikram Singh',    email: 'vikram.s@yahoo.com',    phone: '+919543210123', role: 'FREE_MEMBER',    status: 'APPROVED',  membership: 'FREE'    },
  { name: 'Ananya Krishnan', email: 'ananya.k@gmail.com',    phone: '+919432101234', role: 'PREMIUM_MEMBER', status: 'APPROVED',  membership: 'PREMIUM' },
  { name: 'Rohan Mehta',     email: 'rohan.m@gmail.com',     phone: '+919321012345', role: 'FREE_MEMBER',    status: 'APPROVED',  membership: 'FREE'    },
  { name: 'Kavya Nair',      email: 'kavya.n@hotmail.com',   phone: '+919210123456', role: 'FREE_MEMBER',    status: 'APPROVED',  membership: 'FREE'    },
  { name: 'Aditya Kumar',    email: 'aditya.k@gmail.com',    phone: '+919109234567', role: 'PREMIUM_MEMBER', status: 'APPROVED',  membership: 'VIP'     },
  { name: 'Divya Reddy',     email: 'divya.r@gmail.com',     phone: '+918998345678', role: 'FREE_MEMBER',    status: 'APPROVED',  membership: 'FREE'    },
  { name: 'Manish Gupta',    email: 'manish.g@gmail.com',    phone: '+918887456789', role: 'FREE_MEMBER',    status: 'PENDING',   membership: 'FREE'    },
  { name: 'Shreya Joshi',    email: 'shreya.j@gmail.com',    phone: '+918776567890', role: 'FREE_MEMBER',    status: 'PENDING',   membership: 'FREE'    },
  { name: 'Nikhil Rao',      email: 'nikhil.r@gmail.com',    phone: '+918665678901', role: 'FREE_MEMBER',    status: 'PENDING',   membership: 'FREE'    },
  { name: 'Pooja Iyer',      email: 'pooja.i@gmail.com',     phone: '+918554789012', role: 'FREE_MEMBER',    status: 'PENDING',   membership: 'FREE'    },
  { name: 'Kartik Malhotra', email: 'kartik.m@gmail.com',    phone: '+918443890123', role: 'FREE_MEMBER',    status: 'PENDING',   membership: 'FREE'    },
  { name: 'Ritu Agarwal',    email: 'ritu.a@gmail.com',      phone: '+918332901234', role: 'FREE_MEMBER',    status: 'SUSPENDED', membership: 'FREE'    },
  { name: 'Saurabh Tiwari',  email: 'saurabh.t@gmail.com',   phone: '+918221012345', role: 'FREE_MEMBER',    status: 'SUSPENDED', membership: 'FREE'    },
  { name: 'Nisha Kapoor',    email: 'nisha.k@gmail.com',     phone: '+918110123456', role: 'FREE_MEMBER',    status: 'APPROVED',  membership: 'FREE'    },
  { name: 'Deepak Bose',     email: 'deepak.b@gmail.com',    phone: '+917999234567', role: 'FREE_MEMBER',    status: 'APPROVED',  membership: 'FREE'    },
] as const;

const DEMO_GROUPS = [
  { name: 'General Discussion',    description: 'Open discussions about anything community-related.',                  type: 'PUBLIC'  },
  { name: 'Premium Lounge',        description: 'Exclusive space for premium and VIP members.',                        type: 'PREMIUM' },
  { name: 'Tech & Innovation',     description: 'Talk about the latest in technology, startups, and digital trends.',  type: 'PUBLIC'  },
  { name: 'Wellness & Fitness',    description: 'Share workout routines, nutrition tips, and wellness journeys.',       type: 'PUBLIC'  },
  { name: 'Investment Circle',     description: 'Private group for discussing investment strategies and market news.',  type: 'PRIVATE' },
  { name: 'Books & Learning',      description: 'Book recommendations, summaries, and lifelong learning discussions.', type: 'PUBLIC'  },
  { name: 'VIP Masterminds',       description: 'Exclusive mastermind sessions for VIP members.',                      type: 'PREMIUM' },
  { name: 'Events & Meetups',      description: 'Coordinate and discuss upcoming community events and meetups.',        type: 'PUBLIC'  },
] as const;

const TEXT_POSTS = [
  'Just wrapped up an incredible networking session with fellow members. The energy in this community never ceases to amaze me! 🙌',
  'Reminder: Success is not final, failure is not fatal — it is the courage to continue that counts. Keep going everyone!',
  'Had a breakthrough moment today during my morning meditation. Clarity comes when you slow down. Grateful for this community\'s support.',
  'Three things I learned this week: 1) Consistency beats intensity 2) Network is net worth 3) Rest is productive. What did you learn?',
  'The best investment you can ever make is in yourself. Education, health, relationships — these compound over time like nothing else.',
  'Finished reading Atomic Habits last night. The concept of 1% better every day is truly life-changing. Highly recommend it.',
  'Can we talk about how underrated early mornings are? The world is quiet, the mind is sharp, and you own the day before it begins.',
  'Gratitude post: Thank you to everyone who has supported my journey here. This community has added so much value to my life.',
  'Hot take: The most successful people are not the smartest — they are the most disciplined. Discipline over motivation, always.',
  'Working from a café today and realized I am 40% more productive here than at my home office. Environment really does matter.',
];

const ANNOUNCEMENT_POSTS = [
  'IMPORTANT: Our annual community summit is coming up on June 15th. Register now to secure your spot — limited seats available!',
  'New feature alert! You can now share PDF documents directly in the feed. Perfect for sharing reports, whitepapers, and ebooks.',
  'Welcome to all our new members who joined this week! Please introduce yourself in the General Discussion group.',
  'Community guidelines update: Please review the updated code of conduct pinned at the top of every group.',
  'Congratulations to this month\'s top contributors: Priya Sharma, Aditya Kumar, and Ananya Krishnan — thank you for keeping things lively!',
];

const LINK_POSTS = [
  { body: 'Must-read: How India\'s startup ecosystem is evolving in 2025', url: 'https://yourstory.com/2025/startup-india-evolution' },
  { body: 'The science of habit formation — a deep dive into neuroplasticity', url: 'https://hubermanlab.com/habit-formation' },
  { body: 'Warren Buffett\'s annual shareholder letter is out — key takeaways inside', url: 'https://berkshirehathaway.com/letters/2024' },
];

const EVENT_POSTS = [
  { name: 'Community Networking Night', date: '2025-06-15', time: '18:00', location: 'The Grand Ballroom, Mumbai', description: 'Join us for an evening of meaningful connections, inspiring conversations, and excellent food.' },
  { name: 'Digital Marketing Masterclass', date: '2025-06-22', time: '10:00', location: 'Online (Zoom)', description: 'Learn cutting-edge digital marketing strategies from industry experts. Open to all premium members.' },
  { name: 'Weekend Wellness Retreat', date: '2025-07-05', time: '08:00', location: 'Lonavala, Maharashtra', description: 'A weekend of yoga, meditation, and reconnecting with nature. Limited to 30 participants.' },
  { name: 'Startup Pitch Day', date: '2025-07-12', time: '14:00', location: 'WeWork, Bandra Kurla Complex', description: 'Watch community members pitch their startups to a panel of investors. Free to attend.' },
  { name: 'Annual Members Gala', date: '2025-08-01', time: '19:00', location: 'JW Marriott, Juhu', description: 'Our flagship annual celebration — awards, keynotes, and networking dinner.' },
];

const POLL_DATA = [
  {
    question: 'What is the biggest challenge you face as a professional?',
    options: ['Work-life balance', 'Finding the right opportunities', 'Building a strong network', 'Managing finances'],
  },
  {
    question: 'Which format do you prefer for community events?',
    options: ['In-person only', 'Online only', 'Hybrid (both)', 'No preference'],
  },
  {
    question: 'How often do you read non-fiction books?',
    options: ['Every week', 'Once a month', 'A few times a year', 'Rarely'],
  },
  {
    question: 'What topic would you like more content about?',
    options: ['Personal finance & investing', 'Entrepreneurship & startups', 'Health & wellness', 'Leadership & management'],
  },
  {
    question: 'Which morning habit has the biggest impact on your day?',
    options: ['Exercise / gym', 'Meditation / mindfulness', 'Reading / journaling', 'Planning the day'],
  },
];

const GROUP_MESSAGES = [
  'Hey everyone! Great to be here 👋',
  'Has anyone been to the last networking event? How was it?',
  'Just sharing this article I found — really insightful stuff on productivity.',
  'Reminder about tomorrow\'s call — details in the pinned message above.',
  'Love the energy in this group! Keep it up everyone 🔥',
  'Question for the group: what\'s your best morning routine tip?',
  'Just closed a deal today! This community\'s advice helped a lot. Thank you all!',
  'Anyone attending the gala in August? Would love to meet IRL.',
  'New resource shared in the Files section — check it out when you get a chance.',
  'Weekly check-in: What is one win you had this week? Drop it below ⬇️',
  'Pro tip: Block 90-minute deep work sessions, then take a 15-min break. Game changer.',
  'Can we plan a virtual coffee chat this weekend? Drop a ✅ if interested.',
  'Reading recommendations anyone? I just finished The Psychology of Money.',
  'Shoutout to the admins for keeping this community so well-organized!',
  'Who else uses Notion for project management? Looking for templates.',
];

const COMMENTS = [
  'Totally agree with this! 💯',
  'This is so inspiring, thank you for sharing!',
  'Could not have said it better myself.',
  'Just what I needed to read today.',
  'Sharing this with my team right away!',
  'This community is gold. Love posts like this.',
  'Great insight! Keep them coming.',
  'Thank you for the reminder. Setting my alarm for 5am tomorrow 😄',
  'Been following this principle for a year now — life changing.',
  'Any resources you recommend on this topic?',
  'Would love to discuss this more in the group chat!',
  'Pinned this for later. So relevant!',
];

// ─── Main ─────────────────────────────────────────────────────────────────────

async function main() {
  console.log('🌱 Starting seed...\n');

  // ── 1. Users ──────────────────────────────────────────────────────────────
  console.log('👥 Creating users...');
  const createdUsers: { id: string; name: string; role: string }[] = [];

  for (const u of DEMO_USERS) {
    const existing = await prisma.user.findFirst({
      where: { OR: [u.email ? { email: u.email } : undefined, u.phone ? { phone: u.phone } : undefined].filter(Boolean) as any[] },
    });

    const passwordHash = (u as any).password ? await bcrypt.hash((u as any).password, 10) : await bcrypt.hash('Demo@1234', 10);

    if (existing) {
      // Always update password + status so re-running seed fixes credential issues
      await prisma.user.update({
        where: { id: existing.id },
        data: { passwordHash, status: u.status as any, role: u.role as any },
      });
      createdUsers.push({ id: existing.id, name: existing.name, role: u.role });
      console.log(`  🔄 ${u.name} (updated password & status)`);
      continue;
    }

    const user = await prisma.user.create({
      data: {
        name: u.name,
        email: u.email ?? null,
        phone: u.phone ?? null,
        passwordHash,
        role: u.role as any,
        status: u.status as any,
        bio: `Hi, I'm ${u.name}. Excited to be part of this community!`,
        membership: { create: { type: u.membership as any } },
      },
    });
    createdUsers.push({ id: user.id, name: user.name, role: user.role });
    console.log(`  ✅ ${u.name} (${u.role} / ${u.status})`);
  }

  const adminUser = createdUsers.find((u) => u.role === 'SUPER_ADMIN')!;
  const modUser   = createdUsers.find((u) => u.role === 'MODERATOR')!;
  const approvedUsers = createdUsers.filter((_, i) => DEMO_USERS[i]?.status === 'APPROVED');

  // ── 2. Groups ─────────────────────────────────────────────────────────────
  console.log('\n💬 Creating groups...');
  const createdGroups: { id: string; name: string; type: string }[] = [];

  for (const g of DEMO_GROUPS) {
    const existing = await prisma.group.findFirst({ where: { name: g.name } });
    if (existing) {
      createdGroups.push({ id: existing.id, name: existing.name, type: existing.type });
      console.log(`  ⏭  ${g.name} (already exists)`);
      continue;
    }
    const group = await prisma.group.create({
      data: { name: g.name, description: g.description, type: g.type as any, createdById: adminUser.id },
    });
    createdGroups.push({ id: group.id, name: group.name, type: group.type });
    console.log(`  ✅ ${g.name} (${g.type})`);
  }

  // ── 3. Group memberships ──────────────────────────────────────────────────
  console.log('\n🤝 Adding group members...');
  for (const group of createdGroups) {
    // Admin is in every group
    const memberIds = [adminUser.id, modUser.id, ...approvedUsers.map((u) => u.id)];
    // Premium/private groups only get premium/VIP users
    const eligibleIds = group.type === 'PUBLIC'
      ? memberIds
      : memberIds.filter((_, i) => i < 6); // admin, mod, and first 4 approved

    for (const userId of eligibleIds) {
      await prisma.groupMember.upsert({
        where: { groupId_userId: { groupId: group.id, userId } },
        update: {},
        create: { groupId: group.id, userId, role: userId === adminUser.id ? 'admin' : 'member' },
      });
    }
    console.log(`  ✅ ${group.name} — ${eligibleIds.length} members`);
  }

  // ── 4. Feed posts ─────────────────────────────────────────────────────────
  console.log('\n📝 Creating feed posts...');

  const postAuthors = [adminUser, modUser, ...approvedUsers.slice(0, 8)];

  // Check if we already have feed posts
  const existingPostCount = await prisma.feed.count();
  if (existingPostCount > 0) {
    console.log(`  ⏭  Feed posts already exist (${existingPostCount} found), skipping.`);
  } else {
    let postCount = 0;

    // TEXT posts
    for (let i = 0; i < TEXT_POSTS.length; i++) {
      const author = postAuthors[i % postAuthors.length];
      await prisma.feed.create({
        data: {
          authorId: author.id,
          contentType: 'TEXT',
          body: TEXT_POSTS[i],
          pinned: i === 0,
          createdAt: daysAgo(TEXT_POSTS.length - i),
        },
      });
      postCount++;
    }
    console.log(`  ✅ ${TEXT_POSTS.length} TEXT posts`);

    // ANNOUNCEMENT posts
    for (let i = 0; i < ANNOUNCEMENT_POSTS.length; i++) {
      await prisma.feed.create({
        data: {
          authorId: adminUser.id,
          contentType: 'ANNOUNCEMENT',
          body: ANNOUNCEMENT_POSTS[i],
          pinned: i === 0,
          createdAt: daysAgo(ANNOUNCEMENT_POSTS.length - i + 5),
        },
      });
      postCount++;
    }
    console.log(`  ✅ ${ANNOUNCEMENT_POSTS.length} ANNOUNCEMENT posts`);

    // LINK posts
    for (let i = 0; i < LINK_POSTS.length; i++) {
      const author = postAuthors[i % postAuthors.length];
      await prisma.feed.create({
        data: {
          authorId: author.id,
          contentType: 'LINK',
          body: LINK_POSTS[i].body,
          mediaUrls: [LINK_POSTS[i].url],
          createdAt: daysAgo(i + 2),
        },
      });
      postCount++;
    }
    console.log(`  ✅ ${LINK_POSTS.length} LINK posts`);

    // EVENT posts
    for (let i = 0; i < EVENT_POSTS.length; i++) {
      const author = i === 0 ? adminUser : postAuthors[i % postAuthors.length];
      await prisma.feed.create({
        data: {
          authorId: author.id,
          contentType: 'EVENT',
          body: JSON.stringify(EVENT_POSTS[i]),
          createdAt: daysAgo(EVENT_POSTS.length - i + 1),
        },
      });
      postCount++;
    }
    console.log(`  ✅ ${EVENT_POSTS.length} EVENT posts`);

    // POLL posts
    const createdPolls: string[] = [];
    for (let i = 0; i < POLL_DATA.length; i++) {
      const p = POLL_DATA[i];
      const author = postAuthors[i % postAuthors.length];
      const feed = await prisma.feed.create({
        data: {
          authorId: author.id,
          contentType: 'POLL',
          body: p.question,
          createdAt: daysAgo(POLL_DATA.length - i + 3),
          poll: {
            create: {
              question: p.question,
              endsAt: daysFromNow(7 + i * 3),
              options: { create: p.options.map((text) => ({ text })) },
            },
          },
        },
      });
      createdPolls.push(feed.id);
      postCount++;
    }
    console.log(`  ✅ ${POLL_DATA.length} POLL posts`);

    // IMAGE posts (placeholder URLs — real images need upload)
    const imagePosts = [
      { body: 'Beautiful morning at the office today! Grateful for the amazing view. 🌅', urls: ['https://images.unsplash.com/photo-1497366216548-37526070297c?w=800'] },
      { body: 'Team lunch to celebrate our Q1 wins! 🎉', urls: ['https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?w=800'] },
      { body: 'New workspace setup — finally got the standing desk I wanted! 💻', urls: ['https://images.unsplash.com/photo-1593642632559-0c6d3fc62b89?w=800'] },
      { body: 'Highlights from last week\'s community meetup — what a night! 🙌', urls: [
        'https://images.unsplash.com/photo-1540575467063-178a50c2df87?w=800',
        'https://images.unsplash.com/photo-1511578314322-379afb476865?w=800',
      ]},
      { body: 'Morning run done ✅ 5km in 28 minutes — new personal best!', urls: ['https://images.unsplash.com/photo-1552674605-db6ffd4facb5?w=800'] },
    ];
    for (let i = 0; i < imagePosts.length; i++) {
      const author = postAuthors[(i + 2) % postAuthors.length];
      await prisma.feed.create({
        data: {
          authorId: author.id,
          contentType: 'IMAGE',
          body: imagePosts[i].body,
          mediaUrls: imagePosts[i].urls,
          createdAt: daysAgo(imagePosts.length - i),
        },
      });
      postCount++;
    }
    console.log(`  ✅ ${imagePosts.length} IMAGE posts`);

    // PDF posts
    const pdfPosts = [
      { body: 'Sharing our community handbook — everything you need to know!', url: 'https://example.com/community-handbook.pdf' },
      { body: 'Monthly newsletter — May 2025 edition is here!', url: 'https://example.com/newsletter-may-2025.pdf' },
      { body: 'Investment guide for beginners — worth a read over the weekend.', url: 'https://example.com/investment-guide-beginners.pdf' },
    ];
    for (let i = 0; i < pdfPosts.length; i++) {
      await prisma.feed.create({
        data: {
          authorId: adminUser.id,
          contentType: 'PDF',
          body: pdfPosts[i].body,
          mediaUrls: [pdfPosts[i].url],
          createdAt: daysAgo(i + 7),
        },
      });
      postCount++;
    }
    console.log(`  ✅ ${pdfPosts.length} PDF posts`);

    // VIDEO posts
    const videoPosts = [
      { body: 'Watch this powerful 10-minute talk on building resilience. Bookmarked for life.', url: 'https://example.com/resilience-talk.mp4' },
      { body: 'Behind-the-scenes from our last event — the energy was unreal! 🎬', url: 'https://example.com/event-highlights.mp4' },
    ];
    for (let i = 0; i < videoPosts.length; i++) {
      const author = postAuthors[i % postAuthors.length];
      await prisma.feed.create({
        data: {
          authorId: author.id,
          contentType: 'VIDEO',
          body: videoPosts[i].body,
          mediaUrls: [videoPosts[i].url],
          createdAt: daysAgo(i + 4),
        },
      });
      postCount++;
    }
    console.log(`  ✅ ${videoPosts.length} VIDEO posts`);

    console.log(`\n  📊 Total posts created: ${postCount}`);

    // ── 5. Reactions & Comments ───────────────────────────────────────────
    const allPosts = await prisma.feed.findMany({ select: { id: true }, take: 40 });
    const reactionTypes = ['❤️', '👍', '🔥', '🎉', '💯'];
    let reactionCount = 0, commentCount = 0;

    for (const post of allPosts) {
      const reactors = shuffle(approvedUsers).slice(0, pick(3, 8));
      for (const user of reactors) {
        await prisma.feedReaction.upsert({
          where: { feedId_userId: { feedId: post.id, userId: user.id } },
          update: {},
          create: { feedId: post.id, userId: user.id, reactionType: reactionTypes[Math.floor(Math.random() * reactionTypes.length)] },
        });
        reactionCount++;
      }

      const commentors = shuffle(approvedUsers).slice(0, pick(1, 3));
      for (const user of commentors) {
        await prisma.feedComment.create({
          data: { feedId: post.id, userId: user.id, body: COMMENTS[Math.floor(Math.random() * COMMENTS.length)] },
        });
        commentCount++;
      }
    }
    console.log(`  ✅ ${reactionCount} reactions, ${commentCount} comments`);

    // ── 6. Poll votes ─────────────────────────────────────────────────────
    const polls = await prisma.poll.findMany({ include: { options: true } });
    let voteCount = 0;
    for (const poll of polls) {
      const voters = shuffle(approvedUsers).slice(0, pick(4, 10));
      for (const user of voters) {
        const option = poll.options[Math.floor(Math.random() * poll.options.length)];
        await prisma.pollVote.upsert({
          where: { pollOptionId_userId: { pollOptionId: option.id, userId: user.id } },
          update: {},
          create: { pollOptionId: option.id, userId: user.id },
        });
        voteCount++;
      }
    }
    console.log(`  ✅ ${voteCount} poll votes`);
  }

  // ── 7. Group messages ──────────────────────────────────────────────────────
  console.log('\n💬 Creating group messages...');
  const existingMsgCount = await prisma.message.count();
  if (existingMsgCount > 0) {
    console.log(`  ⏭  Messages already exist (${existingMsgCount} found), skipping.`);
  } else {
    let msgCount = 0;
    for (const group of createdGroups) {
      const members = await prisma.groupMember.findMany({ where: { groupId: group.id }, select: { userId: true } });
      const memberIds = members.map((m) => m.userId);

      for (let i = 0; i < GROUP_MESSAGES.length; i++) {
        const userId = memberIds[i % memberIds.length];
        await prisma.message.create({
          data: {
            groupId: group.id,
            userId,
            type: 'TEXT',
            body: GROUP_MESSAGES[i],
            createdAt: daysAgo(GROUP_MESSAGES.length - i),
          },
        });
        msgCount++;
      }
      console.log(`  ✅ ${group.name} — ${GROUP_MESSAGES.length} messages`);
    }
    console.log(`  📊 Total messages: ${msgCount}`);
  }

  // ── 8. Member profiles ────────────────────────────────────────────────────
  console.log('\n🧑‍💼 Seeding member profiles...');

  const PROFILES: Record<string, {
    headline: string; bio: string; profession: string; company: string;
    location: string; linkedin: string; website?: string;
    skills: string[]; hobbies: string[];
    achievements: { title: string; year: string; description: string }[];
  }> = {
    'priya.sharma@gmail.com': {
      headline: 'Marketing Director | Brand Strategist | TEDx Speaker',
      bio: 'Passionate about building brands that connect with people at a deeper level. 12 years in marketing across FMCG, tech, and D2C. I believe great communities are built on authentic stories.',
      profession: 'Marketing Director',
      company: 'BrandCraft India',
      location: 'Mumbai, Maharashtra',
      linkedin: 'https://linkedin.com/in/priyasharma',
      website: 'https://priyasharma.in',
      skills: ['Brand Strategy', 'Digital Marketing', 'Content Creation', 'SEO', 'Team Leadership'],
      hobbies: ['Photography', 'Yoga', 'Travel', 'Book Club'],
      achievements: [
        { title: 'TEDx Speaker — "The Power of Authentic Branding"', year: '2023', description: 'Spoke to an audience of 800 at TEDxMumbai on brand authenticity.' },
        { title: 'Marketing Leader of the Year — IAMAI', year: '2022', description: 'Recognised by the Internet & Mobile Association of India.' },
        { title: 'Forbes 30 Under 30 — Marketing & Advertising', year: '2020', description: 'Listed among India\'s top young marketing professionals.' },
      ],
    },
    'rahul.v@outlook.com': {
      headline: 'Serial Entrepreneur | Angel Investor | 3x Founder',
      bio: 'Founded and exited two SaaS companies. Now investing in early-stage startups and mentoring the next generation of Indian founders. Deeply interested in EdTech and FinTech.',
      profession: 'Founder & CEO',
      company: 'Verma Ventures',
      location: 'Bengaluru, Karnataka',
      linkedin: 'https://linkedin.com/in/rahulverma',
      website: 'https://rahulverma.com',
      skills: ['Entrepreneurship', 'Venture Capital', 'Product Strategy', 'Fundraising', 'SaaS', 'Leadership'],
      hobbies: ['Chess', 'Long-distance Running', 'Podcasting', 'Reading'],
      achievements: [
        { title: 'Successful Exit — EduFlow (acquired by Byju\'s)', year: '2021', description: 'Led EduFlow from 0 to $8M ARR before acquisition.' },
        { title: 'Nasscom Emerge 50 — Top Indian Startups', year: '2019', description: 'EduFlow named among top 50 emerging Indian startups.' },
        { title: 'IIT Bombay — Gold Medalist, Computer Science', year: '2012', description: 'Graduated top of the batch with specialisation in AI.' },
      ],
    },
    'ananya.k@gmail.com': {
      headline: 'Chartered Accountant | Financial Advisor | Wealth Coach',
      bio: 'CA with 9 years of experience in personal finance, tax planning, and wealth management. I help professionals and entrepreneurs take control of their financial future. Simplifying money — one conversation at a time.',
      profession: 'Chartered Accountant & Financial Advisor',
      company: 'Krishnan & Associates',
      location: 'Chennai, Tamil Nadu',
      linkedin: 'https://linkedin.com/in/ananyakrishnan',
      skills: ['Financial Planning', 'Tax Advisory', 'Wealth Management', 'GST', 'Audit', 'Investment Strategy'],
      hobbies: ['Carnatic Music', 'Cooking', 'Hiking', 'Journaling'],
      achievements: [
        { title: 'ICAI Rank Holder — CA Final', year: '2015', description: 'Secured All-India Rank 12 in the Chartered Accountancy Final examination.' },
        { title: 'Best CA Practice — South India (SME Category)', year: '2022', description: 'Awarded by the Southern India Regional Council of ICAI.' },
      ],
    },
    'aditya.k@gmail.com': {
      headline: 'CTO | Full-Stack Engineer | AI/ML Enthusiast',
      bio: 'Building the infrastructure of the future. 10+ years in software engineering — from scrappy startups to scaling products to millions of users. Currently leading tech at a Series B fintech.',
      profession: 'Chief Technology Officer',
      company: 'FinStack Technologies',
      location: 'Hyderabad, Telangana',
      linkedin: 'https://linkedin.com/in/adityakumar-tech',
      website: 'https://adityakumar.dev',
      skills: ['System Architecture', 'React Native', 'Node.js', 'AWS', 'Machine Learning', 'TypeScript', 'PostgreSQL'],
      hobbies: ['Open Source Contributions', 'Gaming', 'Badminton', 'Science Fiction'],
      achievements: [
        { title: 'GitHub Star — 2,400+ stars on open-source project', year: '2023', description: 'Built and maintained a widely-used React Native UI library.' },
        { title: 'Speaker — ReactConf India', year: '2022', description: 'Presented on "Scaling Mobile Applications to 10M Users".' },
        { title: 'Microsoft MVP — Developer Technologies', year: '2021', description: 'Recognised by Microsoft for contributions to the developer community.' },
      ],
    },
    'sneha.p@gmail.com': {
      headline: 'HR Leader | People & Culture | Executive Coach',
      bio: 'I build workplaces where people actually want to come to work. 8 years in HR leadership across tech startups and MNCs. Certified executive coach and advocate for mental health at work.',
      profession: 'Head of People & Culture',
      company: 'GrowthHive Startup Studio',
      location: 'Pune, Maharashtra',
      linkedin: 'https://linkedin.com/in/snehapatel-hr',
      skills: ['Talent Acquisition', 'Employee Engagement', 'Executive Coaching', 'OKR Implementation', 'Diversity & Inclusion'],
      hobbies: ['Pottery', 'Marathon Running', 'Volunteering', 'Mindfulness'],
      achievements: [
        { title: 'Best Workplace Initiative — People Matters HR Award', year: '2023', description: 'Led a mental health programme that reduced attrition by 35%.' },
        { title: 'ICF Certified Executive Coach', year: '2021', description: 'Internationally certified by the International Coaching Federation.' },
      ],
    },
    'vikram.s@yahoo.com': {
      headline: 'Real Estate Developer | Urban Infrastructure | Smart Cities',
      bio: 'Developing sustainable residential and commercial spaces across Tier 1 and Tier 2 Indian cities. Believer in community-first urban development. 15 years in real estate.',
      profession: 'Managing Director',
      company: 'Singh Infracon Pvt. Ltd.',
      location: 'Delhi, NCR',
      linkedin: 'https://linkedin.com/in/vikramsingh-realty',
      skills: ['Real Estate Development', 'Project Management', 'Urban Planning', 'Negotiation', 'RERA Compliance'],
      hobbies: ['Golf', 'Architecture & Design', 'Travelling', 'Cricket'],
      achievements: [
        { title: 'CREDAI Young Leader Award', year: '2022', description: 'Recognised by the Confederation of Real Estate Developers.' },
        { title: 'Delivered 1,200+ residential units across 4 cities', year: '2023', description: 'Projects in Delhi, Noida, Lucknow, and Jaipur.' },
      ],
    },
    'rohan.m@gmail.com': {
      headline: 'Creative Director | Advertising | Storytelling',
      bio: 'Telling stories that move people. Creative Director at a Cannes-shortlisted agency. I believe the best advertising doesn\'t feel like advertising.',
      profession: 'Creative Director',
      company: 'Pixel & Pen Creative Agency',
      location: 'Mumbai, Maharashtra',
      linkedin: 'https://linkedin.com/in/rohanmehta-creative',
      skills: ['Copywriting', 'Art Direction', 'Campaign Strategy', 'Video Production', 'Brand Identity'],
      hobbies: ['Street Photography', 'Music Production', 'Cinema', 'Sketching'],
      achievements: [
        { title: 'Cannes Lions Shortlist — Film Craft', year: '2023', description: 'Campaign "Voices of India" shortlisted at the world\'s most prestigious advertising awards.' },
        { title: 'Abby Award — Gold, Social Media Campaign', year: '2022', description: 'Goafest Abbys Gold for Best Social Media Campaign.' },
      ],
    },
    'divya.r@gmail.com': {
      headline: 'Physician | Public Health Advocate | Healthcare Entrepreneur',
      bio: 'MBBS, MD (Internal Medicine). After 7 years in clinical practice, I co-founded a digital health startup focused on making quality primary care accessible in rural India. Passion for preventive medicine.',
      profession: 'Co-Founder & Chief Medical Officer',
      company: 'Sehatmand Health Technologies',
      location: 'Bengaluru, Karnataka',
      linkedin: 'https://linkedin.com/in/divyareddy-health',
      skills: ['Clinical Medicine', 'Public Health', 'Telemedicine', 'Healthcare Policy', 'Medical Education'],
      hobbies: ['Bharatanatyam', 'Trekking', 'Cooking', 'Reading Medical Journals'],
      achievements: [
        { title: 'Social Impact Startup — NASSCOM Foundation Award', year: '2023', description: 'Sehatmand recognised for impact in rural healthcare delivery.' },
        { title: 'WHO Fellowship — Global Health Leadership', year: '2020', description: 'Selected for a competitive WHO leadership programme in Geneva.' },
        { title: 'Gold Medal — MD Internal Medicine, AIIMS Delhi', year: '2017', description: 'Top performer in postgraduate medical examination.' },
      ],
    },
    'nisha.k@gmail.com': {
      headline: 'Fashion Designer | Sustainable Fashion | Founder',
      bio: 'Designing clothes that celebrate Indian craftsmanship and modern silhouettes. My label Niha uses only handwoven fabrics and natural dyes. Sustainability is not a trend — it\'s a responsibility.',
      profession: 'Founder & Head Designer',
      company: 'Niha — Conscious Fashion',
      location: 'Jaipur, Rajasthan',
      linkedin: 'https://linkedin.com/in/nishakapoor-fashion',
      website: 'https://nihalabel.com',
      skills: ['Fashion Design', 'Textile Knowledge', 'Sustainable Sourcing', 'Brand Building', 'E-commerce'],
      hobbies: ['Pottery', 'Block Printing', 'Art Collecting', 'Organic Gardening'],
      achievements: [
        { title: 'Lakme Fashion Week — Featured Designer', year: '2023', description: 'Showcased "Ritu" collection at Lakme Fashion Week Summer/Resort 2023.' },
        { title: 'Vogue India — 10 Designers to Watch', year: '2022', description: 'Listed as one of India\'s most exciting emerging fashion talents.' },
      ],
    },
    'deepak.b@gmail.com': {
      headline: 'Supply Chain Expert | Logistics | Global Operations',
      bio: 'Optimising the flow of goods across global supply chains. 14 years managing operations for FMCG, pharma, and e-commerce companies. Currently leading India operations for a multinational logistics firm.',
      profession: 'Vice President — India Operations',
      company: 'GlobalFreight Logistics',
      location: 'Kolkata, West Bengal',
      linkedin: 'https://linkedin.com/in/deepakbose-supply',
      skills: ['Supply Chain Management', 'Warehousing', 'Last-Mile Delivery', 'ERP Systems', 'Team Management', 'Cost Optimisation'],
      hobbies: ['Football', 'Cooking Bengali Cuisine', 'Travel', 'Documentary Films'],
      achievements: [
        { title: 'Supply Chain Professional of the Year — CSCMP India', year: '2022', description: 'Recognised by the Council of Supply Chain Management Professionals.' },
        { title: 'Cost Reduction Award — GlobalFreight Asia Pacific', year: '2021', description: 'Led initiative saving ₹4.2 Cr annually in warehouse operations.' },
      ],
    },
  };

  let profileCount = 0;
  for (const [email, profile] of Object.entries(PROFILES)) {
    const user = await prisma.user.findUnique({ where: { email } });
    if (!user) continue;
    await prisma.user.update({
      where: { id: user.id },
      data: profile as any,
    });
    profileCount++;
    console.log(`  ✅ ${user.name} — profile updated`);
  }
  console.log(`  📊 ${profileCount} profiles seeded`);

  // ── Summary ───────────────────────────────────────────────────────────────
  const [uCount, gCount, fCount, mCount, rCount, cCount, vCount] = await Promise.all([
    prisma.user.count(),
    prisma.group.count(),
    prisma.feed.count(),
    prisma.message.count(),
    prisma.feedReaction.count(),
    prisma.feedComment.count(),
    prisma.pollVote.count(),
  ]);

  console.log('\n✅ Seed complete!');
  console.log('─────────────────────────────────');
  console.log(`  Users:      ${uCount}`);
  console.log(`  Groups:     ${gCount}`);
  console.log(`  Feed posts: ${fCount}`);
  console.log(`  Messages:   ${mCount}`);
  console.log(`  Reactions:  ${rCount}`);
  console.log(`  Comments:   ${cCount}`);
  console.log(`  Poll votes: ${vCount}`);
  console.log('─────────────────────────────────');
  console.log('\n  Admin login → admin@haveyoursay.in / Admin@123');
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

function daysAgo(n: number) {
  return new Date(Date.now() - n * 86_400_000);
}

function daysFromNow(n: number) {
  return new Date(Date.now() + n * 86_400_000);
}

function pick(min: number, max: number) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function shuffle<T>(arr: readonly T[]): T[] {
  const a = [...arr];
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

main()
  .catch(console.error)
  .finally(() => prisma.$disconnect());
