import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { verifyAdminAuth, isSuperAdminSession } from '@/lib/auth';

function hashPassword(password: string): string {
  return Buffer.from(password).toString('base64');
}

export async function POST(request: NextRequest) {
  try {
    // Auth check - only super admins can seed the database
    const authResult = await verifyAdminAuth(request);
    if ('error' in authResult) return authResult.error;

    if (!isSuperAdminSession(authResult.session)) {
      return NextResponse.json(
        { error: 'Only super admins can seed the database' },
        { status: 403 }
      );
    }

    // Seed Users
    const users = await Promise.all([
      db.user.upsert({
        where: { email: 'rahim@example.com' },
        update: {},
        create: {
          name: 'Rahim Uddin',
          email: 'rahim@example.com',
          phone: '+8801712345678',
          password: hashPassword('password123'),
          roles: 'landlord',
          division: 'Dhaka',
          district: 'Dhaka',
          upazila: 'Dhanmondi',
          isVerified: true,
        },
      }),
      db.user.upsert({
        where: { email: 'karim@example.com' },
        update: {},
        create: {
          name: 'Karim Hossain',
          email: 'karim@example.com',
          phone: '+8801798765432',
          password: hashPassword('password123'),
          roles: 'landlord',
          division: 'Dhaka',
          district: 'Dhaka',
          upazila: 'Mirpur',
          isVerified: true,
        },
      }),
      db.user.upsert({
        where: { email: 'nasir@example.com' },
        update: {},
        create: {
          name: 'Nasir Ahmed',
          email: 'nasir@example.com',
          phone: '+8801555123456',
          password: hashPassword('password123'),
          roles: 'landlord',
          division: 'Dhaka',
          district: 'Dhaka',
          upazila: 'Uttara',
          isVerified: true,
        },
      }),
      db.user.upsert({
        where: { email: 'salam@example.com' },
        update: {},
        create: {
          name: 'Salam Sheikh',
          email: 'salam@example.com',
          phone: '+8801612345678',
          password: hashPassword('password123'),
          roles: 'seller',
          division: 'Dhaka',
          district: 'Dhaka',
          upazila: 'Palashi',
          isVerified: true,
        },
      }),
      db.user.upsert({
        where: { email: 'mizan@example.com' },
        update: {},
        create: {
          name: 'Mizan Rahman',
          email: 'mizan@example.com',
          phone: '+8801812345678',
          password: hashPassword('password123'),
          roles: 'landlord',
          division: 'Chittagong',
          district: 'Chittagong',
          upazila: 'Raozan',
          isVerified: true,
        },
      }),
      db.user.upsert({
        where: { email: 'tania@example.com' },
        update: {},
        create: {
          name: 'Tania Akter',
          email: 'tania@example.com',
          phone: '+8801912345678',
          password: hashPassword('password123'),
          roles: 'landlord',
          division: 'Dhaka',
          district: 'Dhaka',
          upazila: 'Gulshan',
          isVerified: true,
        },
      }),
      db.user.upsert({
        where: { email: 'demo@needyfy.com' },
        update: {},
        create: {
          name: 'Demo User',
          email: 'demo@needyfy.com',
          phone: '+8801500000000',
          password: hashPassword('demo123'),
          roles: 'general',
          division: 'Dhaka',
          district: 'Dhaka',
          isVerified: true,
        },
      }),
      db.user.upsert({
        where: { email: 'owner@needyfy.com' },
        update: {},
        create: {
          name: 'House Owner Demo',
          email: 'owner@needyfy.com',
          phone: '+8801600000000',
          password: hashPassword('owner123'),
          roles: 'houseOwner',
          division: 'Dhaka',
          district: 'Dhaka',
          upazila: 'Dhanmondi',
          isVerified: true,
        },
      }),
      db.user.upsert({
        where: { email: 'shopowner@needyfy.com' },
        update: {},
        create: {
          name: 'Shop Owner Demo',
          email: 'shopowner@needyfy.com',
          phone: '+8801700000000',
          password: hashPassword('shop123'),
          roles: 'shopOwner',
          division: 'Dhaka',
          district: 'Dhaka',
          upazila: 'Banani',
          isVerified: true,
        },
      }),
      db.user.upsert({
        where: { email: 'admin@needyfy.com' },
        update: {},
        create: {
          name: 'Admin',
          email: 'admin@needyfy.com',
          phone: '+8801800000000',
          password: hashPassword('admin123'),
          roles: 'admin',
          division: 'Dhaka',
          district: 'Dhaka',
          isVerified: true,
        },
      }),
    ]);

    const [u1, u2, u3, u4, u5, u6, demoUser, ownerDemo, shopOwnerDemo, _adminDemo] = users;

    // Seed Houses
    const housesData = [
      {
        title: 'Modern 3BHK Flat in Dhanmondi',
        description: 'Beautiful 3 bedroom flat with modern amenities, near Dhanmondi Lake. Perfect for families with kids. Gas, water, and electricity included.',
        price: 25000,
        rooms: 3,
        bathrooms: 2,
        area: 1200,
        floor: '4th',
        houseType: 'flat',
        rentType: 'family',
        isAvailable: true,
        images: '["/houses/h1.jpg"]',
        address: 'House 12, Road 27, Dhanmondi',
        division: 'Dhaka',
        district: 'Dhaka',
        upazila: 'Dhanmondi',
        ownerId: u1.id,
      },
      {
        title: 'Cozy Bachelor Room in Mirpur',
        description: 'Single room with attached bathroom, suitable for bachelors. Near Mirpur 10 roundabout. WiFi available.',
        price: 6000,
        rooms: 1,
        bathrooms: 1,
        area: 300,
        floor: '2nd',
        houseType: 'room',
        rentType: 'bachelor',
        isAvailable: true,
        images: '["/houses/h2.jpg"]',
        address: 'Block C, Mirpur 10',
        division: 'Dhaka',
        district: 'Dhaka',
        upazila: 'Mirpur',
        ownerId: u2.id,
      },
      {
        title: 'Spacious Family House in Uttara',
        description: 'Large 4 bedroom house with garden and parking space. Located in a peaceful residential area of Uttara Sector 7.',
        price: 35000,
        rooms: 4,
        bathrooms: 3,
        area: 2000,
        floor: 'Ground + 1st',
        houseType: 'house',
        rentType: 'family',
        isAvailable: true,
        images: '["/houses/h3.jpg"]',
        address: 'Sector 7, Uttara',
        division: 'Dhaka',
        district: 'Dhaka',
        upazila: 'Uttara',
        ownerId: u3.id,
      },
      {
        title: '2BHK Flat Near BUET',
        description: 'Well-maintained 2 bedroom flat, ideal for students or small families. Walking distance from BUET campus.',
        price: 18000,
        rooms: 2,
        bathrooms: 1,
        area: 850,
        floor: '3rd',
        houseType: 'flat',
        rentType: 'both',
        isAvailable: true,
        images: '["/houses/h4.jpg"]',
        address: 'Road 8, Palashi',
        division: 'Dhaka',
        district: 'Dhaka',
        upazila: 'Palashi',
        ownerId: u4.id,
      },
      {
        title: 'Mess Room for Students in Chittagong',
        description: 'Affordable mess room near Chittagong University. Shared kitchen and bathroom. Meals available on request.',
        price: 4000,
        rooms: 1,
        bathrooms: 1,
        area: 150,
        floor: '1st',
        houseType: 'mess',
        rentType: 'bachelor',
        isAvailable: true,
        images: '["/houses/h5.jpg"]',
        address: 'Near CU Gate, Chittagong',
        division: 'Chittagong',
        district: 'Chittagong',
        upazila: 'Raozan',
        ownerId: u5.id,
      },
      {
        title: 'Luxury Apartment in Gulshan',
        description: 'Premium 3BHK apartment with rooftop access, gym, and 24/7 security in the heart of Gulshan.',
        price: 55000,
        rooms: 3,
        bathrooms: 3,
        area: 1800,
        floor: '8th',
        houseType: 'flat',
        rentType: 'family',
        isAvailable: true,
        images: '["/houses/h6.jpg"]',
        address: 'Gulshan Avenue, Gulshan 2',
        division: 'Dhaka',
        district: 'Dhaka',
        upazila: 'Gulshan',
        ownerId: u6.id,
      },
      {
        title: '2BHK Flat in Dhanmondi',
        description: 'Well-furnished 2 bedroom flat with balcony and parking. Near Dhanmondi 27. Gas & water included.',
        price: 22000,
        rooms: 2,
        bathrooms: 2,
        area: 950,
        floor: '5th',
        houseType: 'flat',
        rentType: 'both',
        isAvailable: true,
        images: '["/houses/h7.jpg"]',
        address: 'Road 27, Dhanmondi',
        division: 'Dhaka',
        district: 'Dhaka',
        upazila: 'Dhanmondi',
        ownerId: ownerDemo.id,
      },
      {
        title: 'Bachelor Room near DU',
        description: 'Single room with attached bath, ideal for university students. WiFi and utilities included.',
        price: 5500,
        rooms: 1,
        bathrooms: 1,
        area: 250,
        floor: '3rd',
        houseType: 'room',
        rentType: 'bachelor',
        isAvailable: true,
        images: '["/houses/h8.jpg"]',
        address: 'Nilkhet, Dhaka',
        division: 'Dhaka',
        district: 'Dhaka',
        upazila: 'Dhanmondi',
        ownerId: ownerDemo.id,
      },
    ];

    await db.house.deleteMany({});
    const houses = await db.house.createMany({ data: housesData });

    // Seed Shops
    const shopsData = [
      {
        title: 'Commercial Shop in New Market',
        description: 'Prime location shop in New Market, high foot traffic. Ideal for clothing, electronics, or food business.',
        price: 40000,
        shopType: 'retail',
        area: 500,
        isAvailable: true,
        images: '["/shops/s1.jpg"]',
        address: 'New Market, Dhaka',
        division: 'Dhaka',
        district: 'Dhaka',
        upazila: 'New Market',
        ownerId: u1.id,
      },
      {
        title: 'Office Space in Banani',
        description: 'Modern office space with AC, WiFi, and meeting room. Perfect for IT companies or startups.',
        price: 30000,
        shopType: 'office',
        area: 800,
        isAvailable: true,
        images: '["/shops/s2.jpg"]',
        address: 'Road 11, Banani',
        division: 'Dhaka',
        district: 'Dhaka',
        upazila: 'Banani',
        ownerId: u2.id,
      },
      {
        title: 'Warehouse in Gazipur',
        description: 'Large warehouse with loading dock, suitable for e-commerce or manufacturing storage.',
        price: 20000,
        shopType: 'warehouse',
        area: 2000,
        isAvailable: true,
        images: '["/shops/s3.jpg"]',
        address: 'Tongi, Gazipur',
        division: 'Dhaka',
        district: 'Gazipur',
        upazila: 'Tongi',
        ownerId: u3.id,
      },
      {
        title: 'Retail Space in Bashundhara City',
        description: 'Premium retail space in Bashundhara City Shopping Mall. Great for fashion or electronics brand.',
        price: 60000,
        shopType: 'retail',
        area: 600,
        isAvailable: true,
        images: '["/shops/s4.jpg"]',
        address: 'Bashundhara City, Panthapath',
        division: 'Dhaka',
        district: 'Dhaka',
        upazila: 'Panthapath',
        ownerId: u4.id,
      },
      {
        title: 'Modern Office in Banani DOHS',
        description: 'Fully furnished office space with parking, WiFi, and 24/7 security. Great for corporate offices.',
        price: 45000,
        shopType: 'office',
        area: 1200,
        isAvailable: true,
        images: '["/shops/s5.jpg"]',
        address: 'Banani DOHS, Road 4',
        division: 'Dhaka',
        district: 'Dhaka',
        upazila: 'Banani',
        ownerId: shopOwnerDemo.id,
      },
      {
        title: 'Retail Shop in Gulshan 2',
        description: 'Street-facing retail shop in prime Gulshan location. High visibility and foot traffic.',
        price: 55000,
        shopType: 'commercial',
        area: 450,
        isAvailable: true,
        images: '["/shops/s6.jpg"]',
        address: 'Gulshan Avenue, Gulshan 2',
        division: 'Dhaka',
        district: 'Dhaka',
        upazila: 'Gulshan',
        ownerId: shopOwnerDemo.id,
      },
    ];

    await db.shop.deleteMany({});
    const shops = await db.shop.createMany({ data: shopsData });

    // Seed Products
    const productsData = [
      {
        title: 'Basmati Rice (5kg)',
        description: 'Premium quality basmati rice, perfect for biryani and pulao.',
        price: 450,
        discount: 10,
        category: 'grocery',
        subcategory: 'Rice',
        images: '["/products/p1.jpg"]',
        stock: 100,
        unit: '5kg',
        isAvailable: true,
        sellerId: u1.id,
      },
      {
        title: 'Wireless Earbuds Pro',
        description: 'Bluetooth 5.0, noise cancellation, 24hr battery life. Water resistant.',
        price: 2500,
        discount: 15,
        category: 'electronics',
        subcategory: 'Audio',
        images: '["/products/p2.jpg"]',
        stock: 50,
        unit: 'piece',
        isAvailable: true,
        sellerId: u2.id,
      },
      {
        title: 'Cotton Saree - Traditional',
        description: 'Hand woven cotton saree with traditional jamdani design. Made in Bangladesh.',
        price: 1800,
        discount: 0,
        category: 'fashion',
        subcategory: 'Saree',
        images: '["/products/p3.jpg"]',
        stock: 25,
        unit: 'piece',
        isAvailable: true,
        sellerId: u3.id,
      },
      {
        title: 'Napa Extra (10 Tablets)',
        description: 'Paracetamol 500mg. Effective for fever and pain relief.',
        price: 45,
        discount: 0,
        category: 'medicine',
        subcategory: 'Pain Relief',
        images: '["/products/p4.jpg"]',
        stock: 500,
        unit: 'box',
        isAvailable: true,
        sellerId: u4.id,
      },
      {
        title: 'HSC Physics Guide 2025',
        description: 'Complete HSC physics guide with MCQ and written questions. Latest syllabus.',
        price: 350,
        discount: 5,
        category: 'books',
        subcategory: 'HSC',
        images: '["/products/p5.jpg"]',
        stock: 200,
        unit: 'piece',
        isAvailable: true,
        sellerId: u5.id,
      },
      {
        title: 'Detergent Powder (1kg)',
        description: 'Premium detergent powder for all types of clothes. Removes tough stains.',
        price: 120,
        discount: 0,
        category: 'daily_needs',
        subcategory: 'Cleaning',
        images: '["/products/p6.jpg"]',
        stock: 300,
        unit: '1kg',
        isAvailable: true,
        sellerId: u6.id,
      },
      {
        title: 'Smart Watch X1',
        description: 'Fitness tracker with heart rate monitor, SpO2, and 7-day battery life.',
        price: 3500,
        discount: 20,
        category: 'electronics',
        subcategory: 'Wearable',
        images: '["/products/p7.jpg"]',
        stock: 30,
        unit: 'piece',
        isAvailable: true,
        sellerId: u2.id,
      },
      {
        title: 'Organic Honey (500ml)',
        description: 'Pure organic honey from Sundarbans. No preservatives.',
        price: 550,
        discount: 0,
        category: 'grocery',
        subcategory: 'Organic',
        images: '["/products/p8.jpg"]',
        stock: 80,
        unit: '500ml',
        isAvailable: true,
        sellerId: u1.id,
      },
      {
        title: 'Seclo 20mg (14 Capsules)',
        description: 'Omeprazole 20mg. Used for gastric ulcer and acid reflux.',
        price: 80,
        discount: 5,
        category: 'medicine',
        subcategory: 'Gastric',
        images: '["/products/p9.jpg"]',
        stock: 300,
        unit: 'box',
        isAvailable: true,
        sellerId: u4.id,
      },
      {
        title: 'Ace 200mg (10 Tablets)',
        description: 'Aceclofenac 200mg. Effective anti-inflammatory for joint and muscle pain.',
        price: 60,
        discount: 0,
        category: 'medicine',
        subcategory: 'Pain Relief',
        images: '["/products/p10.jpg"]',
        stock: 400,
        unit: 'box',
        isAvailable: true,
        sellerId: u4.id,
      },
      {
        title: 'Maxpro 20mg (14 Tablets)',
        description: 'Esomeprazole 20mg. For GERD and peptic ulcer disease.',
        price: 120,
        discount: 10,
        category: 'medicine',
        subcategory: 'Gastric',
        images: '["/products/p11.jpg"]',
        stock: 250,
        unit: 'box',
        isAvailable: true,
        sellerId: u4.id,
      },
      {
        title: 'Fexo 120mg (10 Tablets)',
        description: 'Fexofenadine 120mg. Antihistamine for allergy and hay fever relief.',
        price: 95,
        discount: 0,
        category: 'medicine',
        subcategory: 'Allergy',
        images: '["/products/p12.jpg"]',
        stock: 350,
        unit: 'box',
        isAvailable: true,
        sellerId: u4.id,
      },
      {
        title: 'T-shirt - Premium Cotton',
        description: '100% cotton premium t-shirt, comfortable and breathable.',
        price: 450,
        discount: 25,
        category: 'fashion',
        subcategory: 'T-Shirt',
        images: '["/products/p13.jpg"]',
        stock: 60,
        unit: 'piece',
        isAvailable: true,
        sellerId: u3.id,
      },
      {
        title: 'USB-C Fast Charger 65W',
        description: 'GaN fast charger with USB-C port. Compatible with laptops and phones.',
        price: 1200,
        discount: 12,
        category: 'electronics',
        subcategory: 'Accessories',
        images: '["/products/p14.jpg"]',
        stock: 45,
        unit: 'piece',
        isAvailable: true,
        sellerId: u2.id,
      },
    ];

    await db.product.deleteMany({});
    const products = await db.product.createMany({ data: productsData });

    // Seed MCQ Questions
    const mcqData = [
      {
        question: 'What is the capital of Bangladesh?',
        optionA: 'Chittagong',
        optionB: 'Dhaka',
        optionC: 'Sylhet',
        optionD: 'Rajshahi',
        correctAnswer: 'B',
        category: 'gk',
        topic: 'Bangladesh',
        difficulty: 'easy',
        explanation: 'Dhaka is the capital and largest city of Bangladesh.',
      },
      {
        question: 'What is the chemical formula of water?',
        optionA: 'H2O2',
        optionB: 'HO2',
        optionC: 'H2O',
        optionD: 'OH',
        correctAnswer: 'C',
        category: 'ssc',
        topic: 'Chemistry',
        difficulty: 'easy',
        explanation: 'Water is composed of two hydrogen atoms and one oxygen atom (H2O).',
      },
      {
        question: 'Who wrote "Gitanjali"?',
        optionA: 'Kazi Nazrul Islam',
        optionB: 'Rabindranath Tagore',
        optionC: 'Jasimuddin',
        optionD: 'Sukanta Bhattacharya',
        correctAnswer: 'B',
        category: 'hsc',
        topic: 'Literature',
        difficulty: 'medium',
        explanation: 'Rabindranath Tagore wrote Gitanjali, for which he won the Nobel Prize in Literature in 1913.',
      },
      {
        question: 'What is the value of π (pi) to 2 decimal places?',
        optionA: '3.12',
        optionB: '3.14',
        optionC: '3.16',
        optionD: '3.18',
        correctAnswer: 'B',
        category: 'ssc',
        topic: 'Mathematics',
        difficulty: 'easy',
        explanation: 'The value of π (pi) is approximately 3.14159...',
      },
      {
        question: 'Which planet is known as the Red Planet?',
        optionA: 'Venus',
        optionB: 'Jupiter',
        optionC: 'Mars',
        optionD: 'Saturn',
        correctAnswer: 'C',
        category: 'class6-10',
        topic: 'Science',
        difficulty: 'easy',
        explanation: 'Mars is called the Red Planet due to iron oxide on its surface.',
      },
      {
        question: 'In which year did Bangladesh gain independence?',
        optionA: '1965',
        optionB: '1970',
        optionC: '1971',
        optionD: '1972',
        correctAnswer: 'C',
        category: 'gk',
        topic: 'Bangladesh',
        difficulty: 'easy',
        explanation: 'Bangladesh gained independence on December 16, 1971.',
      },
      {
        question: 'What is the SI unit of force?',
        optionA: 'Joule',
        optionB: 'Watt',
        optionC: 'Newton',
        optionD: 'Pascal',
        correctAnswer: 'C',
        category: 'hsc',
        topic: 'Physics',
        difficulty: 'medium',
        explanation: 'The SI unit of force is Newton (N), named after Sir Isaac Newton.',
      },
      {
        question: 'What is the largest river in Bangladesh?',
        optionA: 'Teesta',
        optionB: 'Meghna',
        optionC: 'Jamuna',
        optionD: 'Padma',
        correctAnswer: 'D',
        category: 'gk',
        topic: 'Bangladesh Geography',
        difficulty: 'medium',
        explanation: 'Padma is the largest river in Bangladesh by water flow.',
      },
      {
        question: 'What does DNA stand for?',
        optionA: 'Deoxyribonucleic Acid',
        optionB: 'Diribonucleic Acid',
        optionC: 'Deoxyribonitric Acid',
        optionD: 'Dinitrogen Acid',
        correctAnswer: 'A',
        category: 'hsc',
        topic: 'Biology',
        difficulty: 'medium',
        explanation: 'DNA stands for Deoxyribonucleic Acid.',
      },
      {
        question: 'If 2x + 5 = 15, what is x?',
        optionA: '4',
        optionB: '5',
        optionC: '6',
        optionD: '10',
        correctAnswer: 'B',
        category: 'ssc',
        topic: 'Mathematics',
        difficulty: 'easy',
        explanation: '2x + 5 = 15 → 2x = 10 → x = 5',
      },
      {
        question: 'What is the powerhouse of the cell?',
        optionA: 'Nucleus',
        optionB: 'Ribosome',
        optionC: 'Mitochondria',
        optionD: 'Golgi Apparatus',
        correctAnswer: 'C',
        category: 'hsc',
        topic: 'Biology',
        difficulty: 'easy',
        explanation: 'Mitochondria is known as the powerhouse of the cell as it produces ATP.',
      },
      {
        question: 'Which gas is most abundant in the atmosphere?',
        optionA: 'Oxygen',
        optionB: 'Carbon Dioxide',
        optionC: 'Nitrogen',
        optionD: 'Hydrogen',
        correctAnswer: 'C',
        category: 'ssc',
        topic: 'Chemistry',
        difficulty: 'easy',
        explanation: 'Nitrogen makes up about 78% of Earth\'s atmosphere.',
      },
      {
        question: 'What is the derivative of sin(x)?',
        optionA: '-cos(x)',
        optionB: 'cos(x)',
        optionC: 'tan(x)',
        optionD: '-sin(x)',
        correctAnswer: 'B',
        category: 'hsc',
        topic: 'Mathematics',
        difficulty: 'hard',
        explanation: 'The derivative of sin(x) is cos(x).',
      },
      {
        question: 'Who discovered penicillin?',
        optionA: 'Louis Pasteur',
        optionB: 'Alexander Fleming',
        optionC: 'Edward Jenner',
        optionD: 'Robert Koch',
        correctAnswer: 'B',
        category: 'gk',
        topic: 'Science History',
        difficulty: 'medium',
        explanation: 'Alexander Fleming discovered penicillin in 1928.',
      },
      {
        question: 'What is the speed of light approximately?',
        optionA: '3 x 10^6 m/s',
        optionB: '3 x 10^8 m/s',
        optionC: '3 x 10^10 m/s',
        optionD: '3 x 10^4 m/s',
        correctAnswer: 'B',
        category: 'hsc',
        topic: 'Physics',
        difficulty: 'hard',
        explanation: 'The speed of light is approximately 3 x 10^8 m/s.',
      },
    ];

    await db.mcqQuestion.deleteMany({});
    const mcqQuestions = await db.mcqQuestion.createMany({ data: mcqData });

    // Seed Locations
    const locationsData = [
      { division: 'Dhaka', district: 'Dhaka', upazila: 'Dhanmondi' },
      { division: 'Dhaka', district: 'Dhaka', upazila: 'Mirpur' },
      { division: 'Dhaka', district: 'Dhaka', upazila: 'Uttara' },
      { division: 'Dhaka', district: 'Dhaka', upazila: 'Gulshan' },
      { division: 'Dhaka', district: 'Dhaka', upazila: 'Banani' },
      { division: 'Dhaka', district: 'Dhaka', upazila: 'Palashi' },
      { division: 'Dhaka', district: 'Gazipur', upazila: 'Tongi' },
      { division: 'Chittagong', district: 'Chittagong', upazila: 'Raozan' },
      { division: 'Chittagong', district: 'Chittagong', upazila: 'Pahartali' },
      { division: 'Rajshahi', district: 'Rajshahi', upazila: 'Rajpara' },
      { division: 'Khulna', district: 'Khulna', upazila: 'Sonadanga' },
      { division: 'Sylhet', district: 'Sylhet', upazila: 'Sadar' },
      { division: 'Barisal', district: 'Barisal', upazila: 'Barisal Sadar' },
      { division: 'Rangpur', district: 'Rangpur', upazila: 'Sadar' },
      { division: 'Mymensingh', district: 'Mymensingh', upazila: 'Sadar' },
    ];

    await db.location.deleteMany({});
    const locations = await db.location.createMany({ data: locationsData });

    // Seed Ad Banners
    const bannersData = [
      {
        title: 'Summer Sale - Up to 50% Off!',
        imageUrl: '/banners/summer-sale.jpg',
        link: '/marketplace?sale=summer',
        position: 'home_top',
        isActive: true,
      },
      {
        title: 'Find Your Dream Home',
        imageUrl: '/banners/house-rental.jpg',
        link: '/house-rental',
        position: 'home_middle',
        isActive: true,
      },
      {
        title: 'MCQ Practice - Free!',
        imageUrl: '/banners/education.jpg',
        link: '/education',
        position: 'home_bottom',
        isActive: true,
      },
    ];

    await db.adBanner.deleteMany({});
    const banners = await db.adBanner.createMany({ data: bannersData });

    // Seed Notifications for demo user
    const notificationsData = [
      {
        userId: demoUser.id,
        title: 'Welcome to Needyfy!',
        message: 'Your account has been created successfully. Explore our services!',
        type: 'admin_notice',
        isRead: false,
      },
      {
        userId: demoUser.id,
        title: 'New House Listed',
        message: 'A new 3BHK flat is available near your location.',
        type: 'house_alert',
        isRead: false,
      },
      {
        userId: demoUser.id,
        title: 'Flash Sale!',
        message: 'Get 20% off on all electronics today.',
        type: 'product_offer',
        isRead: false,
      },
      {
        userId: demoUser.id,
        title: 'MCQ Practice Available',
        message: 'New SSC Mathematics questions have been added.',
        type: 'mcq_update',
        isRead: true,
      },
      {
        userId: demoUser.id,
        title: 'System Update',
        message: 'Needyfy v2.0 is now available with new features!',
        type: 'admin_notice',
        isRead: true,
      },
    ];

    await db.notification.deleteMany({});
    const notifications = await db.notification.createMany({ data: notificationsData });

    // Seed Community Posts
    const communityPostsData = [
      {
        userId: demoUser.id,
        title: 'Best areas for students in Dhaka?',
        content: 'Looking for affordable and safe areas near DU. Any suggestions?',
        postType: 'help',
        likes: 15,
      },
      {
        userId: u1.id,
        title: 'Tips for first-time house renters',
        content: 'Sharing my experience and tips for renting a house in Bangladesh for the first time. Always check the water supply and security situation before signing the lease.',
        postType: 'discussion',
        likes: 42,
      },
      {
        userId: u2.id,
        title: 'Suggestion: Add delivery tracking',
        content: 'It would be great if Needyfy could add real-time delivery tracking for marketplace orders.',
        postType: 'suggestion',
        likes: 28,
      },
    ];

    await db.communityPost.deleteMany({});
    const communityPosts = await db.communityPost.createMany({ data: communityPostsData });

    // Seed some Messages
    const messagesData = [
      {
        senderId: demoUser.id,
        receiverId: u1.id,
        content: 'Hello! I saw your listing for the Dhanmondi flat.',
        messageType: 'text',
      },
      {
        senderId: u1.id,
        receiverId: demoUser.id,
        content: 'Hi! Yes, the flat is available. Are you interested?',
        messageType: 'text',
      },
      {
        senderId: demoUser.id,
        receiverId: u1.id,
        content: 'Yes, I would like to visit. Is this weekend okay?',
        messageType: 'text',
      },
      {
        senderId: u1.id,
        receiverId: demoUser.id,
        content: 'The flat is still available. When can you visit?',
        messageType: 'text',
        isRead: false,
      },
    ];

    await db.message.deleteMany({});
    const messages = await db.message.createMany({ data: messagesData });

    return NextResponse.json({
      message: 'Database seeded successfully!',
      data: {
        users: users.length,
        houses: houses.count,
        shops: shops.count,
        products: products.count,
        mcqQuestions: mcqQuestions.count,
        locations: locations.count,
        banners: banners.count,
        notifications: notifications.count,
        communityPosts: communityPosts.count,
        messages: messages.count,
      },
    }, { status: 201 });
  } catch (error) {
    console.error('Seed error:', error);
    return NextResponse.json(
      { error: 'Failed to seed database' },
      { status: 500 }
    );
  }
}
