/**
 * ============================================================================
 * ChatApp - Database Seed Script
 * Creates test data: 1 workspace, 3 channels, 5 users, 20 messages
 * Usage: npx ts-node scripts/seed.ts
 * ============================================================================
 */

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

const prisma = new PrismaClient();

async function main() {
  console.log('🌱 Seeding database...');

  // --- Create Users (5) ---
  const users = [];
  const userDefs = [
    { email: 'admin@chatapp.dev', display_name: 'Admin User', role: 'owner' },
    { email: 'alice@chatapp.dev', display_name: 'Alice Johnson', role: 'admin' },
    { email: 'bob@chatapp.dev', display_name: 'Bob Smith', role: 'member' },
    { email: 'charlie@chatapp.dev', display_name: 'Charlie Brown', role: 'member' },
    { email: 'diana@chatapp.dev', display_name: 'Diana Prince', role: 'member' },
  ];

  for (const def of userDefs) {
    const passwordHash = await bcrypt.hash('Password123', 12);
    const user = await prisma.user.create({
      data: {
        email: def.email,
        passwordHash,
        displayName: def.display_name,
        timezone: 'UTC',
        locale: 'en',
        isBot: false,
        isDeleted: false,
      },
    });
    users.push({ ...user, role: def.role });
    console.log(`  ✓ User: ${def.email}`);
  }

  // --- Create Workspace (1) ---
  const workspace = await prisma.workspace.create({
    data: {
      name: 'ChatApp Demo',
      domain: 'chatapp-demo',
      plan: 'free',
      maxMembers: 100,
      allowCreateChannels: true,
      allowCustomEmoji: true,
      allowSharedChannels: false,
      enforce2fa: false,
      ssoRequired: false,
      createdBy: users[0].id,
      settings: {
        create: {
          defaultChannel: 'general',
          allowMessageDeletion: true,
          requireLinkPreviews: true,
        },
      },
    },
  });
  console.log(`  ✓ Workspace: ${workspace.name}`);

  // --- Add all users as workspace members ---
  for (const user of users) {
    await prisma.workspaceMember.create({
      data: {
        workspaceId: workspace.id,
        userId: user.id,
        role: user.role,
        joinedAt: new Date(),
      },
    });
  }
  console.log(`  ✓ ${users.length} workspace members added`);

  // --- Create Channels (3) ---
  const channels = [];
  const channelDefs = [
    { name: 'general', handle: 'general', type: 'public', isDefault: true, topic: 'General discussion' },
    { name: 'engineering', handle: 'engineering', type: 'public', isDefault: false, topic: 'Engineering team chat' },
    { name: 'random', handle: 'random', type: 'public', isDefault: false, topic: 'Off-topic fun' },
  ];

  for (const def of channelDefs) {
    const channel = await prisma.channel.create({
      data: {
        workspaceId: workspace.id,
        name: def.name,
        handle: def.handle,
        type: def.type,
        topic: def.topic,
        isDefault: def.isDefault,
        createdBy: users[0].id,
      },
    });
    channels.push(channel);
    console.log(`  ✓ Channel: #${def.name}`);

    // Add all users as channel members
    for (const user of users) {
      await prisma.channelMember.create({
        data: {
          channelId: channel.id,
          userId: user.id,
          workspaceId: workspace.id,
          role: user.role,
          notificationPref: 'all',
        },
      });
    }
  }

  // --- Create Messages (20) ---
  const messages = [
    'Welcome to the general channel! 👋',
    'Has anyone seen the new deployment?',
    'The API is running smoothly now 🚀',
    'I just pushed a fix for the WebSocket reconnection issue',
    'Nice work! The realtime gateway is much more stable.',
    'Can someone review my PR for the message search feature?',
    'I will take a look at it in a few minutes.',
    'Thanks! The Meilisearch integration is working great.',
    'Has anyone tested the file upload with MinIO?',
    'Yes, it works! I uploaded a 50MB file without issues.',
    'The workers are processing notifications faster now.',
    'I noticed the rate limiter is kicking in at 300 req/min.',
    'That is the default. We can adjust it per route.',
    'Let me add a config for that in the next sprint.',
    'The frontend looks great with the new Tailwind theme!',
    'Agreed. The chat interface is much cleaner now.',
    'Is the Docker build working for all services?',
    'Yes, all three Dockerfiles build successfully with multi-stage.',
    'The Prisma migrations are all up to date.',
    'Great job everyone! The app is ready for testing. 🎉',
  ];

  let msgIndex = 0;
  for (const text of messages) {
    const user = users[msgIndex % users.length];
    const channel = channels[msgIndex % channels.length];

    await prisma.message.create({
      data: {
        workspaceId: workspace.id,
        channelId: channel.id,
        userId: user.id,
        text,
        ts: new Date(Date.now() - (20 - msgIndex) * 60000),
      },
    });
    msgIndex++;
  }
  console.log(`  ✓ ${messages.length} messages created`);

  console.log('');
  console.log('✅ Seeding complete!');
  console.log('');
  console.log('Summary:');
  console.log(`  - 1 workspace: ${workspace.name}`);
  console.log(`  - 3 channels: ${channelDefs.map(c => '#' + c.name).join(', ')}`);
  console.log(`  - 5 users: ${userDefs.map(u => u.email).join(', ')}`);
  console.log(`  - 20 messages across all channels`);
  console.log('');
  console.log('Test credentials: email=admin@chatapp.dev password=Password123');
}

main()
  .catch((e) => {
    console.error('❌ Seeding failed:', e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });