import { PrismaClient } from '@prisma/client';
import dotenv from 'dotenv';
import path from 'path';

// Load environment variables - try .env.local first (for host execution), then .env
const envPath = path.resolve(process.cwd(), '.env.local');
const envExists = require('fs').existsSync(envPath);
if (envExists) {
  dotenv.config({ path: envPath, override: true });
  console.log('📁 Using .env.local for host database connection');
} else {
  dotenv.config({ override: true });
  console.log('📁 Using .env for database connection');
}

// Create Prisma client after loading environment variables
const prisma = new PrismaClient({
  log: ['warn', 'error'],
});

export async function seedTestNotifications() {
  console.log('🔔 Starting test data seed for notifications...');

  try {
    // Find the student user
    const student = await prisma.user.findUnique({
      where: { email: 'student@example.com' },
    });

    if (!student) {
      throw new Error('Student user not found. Please run the main seed first.');
    }

    console.log('✅ Student user found:', student.email);

    // Create read notification (older)
    const readNotification = await (prisma as any).notification.create({
      data: {
        userId: student.id,
        title: 'Bot Assigned - English Tutor Sarah',
        message: 'You have been assigned the "English Tutor Sarah" bot to practice basic English conversation. Start practicing now!',
        type: 'BOT_ASSIGNED',
        isRead: true,
        readAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000), // 2 days ago
        createdAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000), // 3 days ago
      },
    });

    console.log('✅ Read notification created:', readNotification.title);

    // Create unread notification (newer)
    const unreadNotification = await (prisma as any).notification.create({
      data: {
        userId: student.id,
        title: 'New Bot Available - Business English Mike',
        message: 'Great news! You have been assigned the "Business English Mike" bot to improve your business English skills. Don\'t forget to check your new assignment!',
        type: 'BOT_ASSIGNED',
        isRead: false,
        createdAt: new Date(Date.now() - 2 * 60 * 60 * 1000), // 2 hours ago
      },
    });

    console.log('✅ Unread notification created:', unreadNotification.title);

    // Verify created notifications
    const notifications = await (prisma as any).notification.findMany({
      where: { userId: student.id },
      orderBy: { createdAt: 'desc' },
    });

    console.log('🎉 Test notifications seed completed successfully!');
    console.log('📊 Created notifications:');
    notifications.forEach((notification, index) => {
      const status = notification.isRead ? '✅ Read' : '🔔 Unread';
      const timeAgo = getTimeAgo(notification.createdAt);
      console.log(`  ${index + 1}. ${notification.title} - ${status} (${timeAgo})`);
    });

  } catch (error) {
    console.error('❌ Error during notifications seed:', error);
    throw error;
  }
}

// Helper function to calculate elapsed time
function getTimeAgo(date: Date): string {
  const now = new Date();
  const diffInMs = now.getTime() - date.getTime();
  const diffInHours = Math.floor(diffInMs / (1000 * 60 * 60));
  const diffInDays = Math.floor(diffInHours / 24);

  if (diffInDays > 0) {
    return `${diffInDays} day${diffInDays > 1 ? 's' : ''} ago`;
  } else if (diffInHours > 0) {
    return `${diffInHours} hour${diffInHours > 1 ? 's' : ''} ago`;
  } else {
    const diffInMinutes = Math.floor(diffInMs / (1000 * 60));
    return `${diffInMinutes} minute${diffInMinutes > 1 ? 's' : ''} ago`;
  }
}

// Main function to run from CLI
async function main() {
  await seedTestNotifications();
}

// Only run main if this file is executed directly
if (require.main === module) {
  main()
    .catch((e) => {
      console.error('❌ Error during notifications seed:', e);
      process.exit(1);
    })
    .finally(async () => {
      await prisma.$disconnect();
    });
}
