import { prisma } from '@/lib/prisma';

async function main() {
  console.log('🌱 Seeding souq demo data...\n');

  // ── Find or create seller user ───────────────────────────────────────────
  let seller = await prisma.user.findFirst();

  if (!seller) {
    console.log('  ℹ️  No users found. Creating a demo seller user...');
    seller = await prisma.user.create({
      data: {
        email: 'demo-seller@falah.app',
        name: 'Demo Seller',
        flhBalance: 10000,
      },
    });
  }
  console.log(`  👤 Seller: ${seller.name} (${seller.email})`);

  // ── Find or create buyer user (needed for purchase → review chain) ───────
  let buyer = await prisma.user.findFirst({ where: { email: 'demo-buyer@falah.app' } });

  if (!buyer) {
    buyer = await prisma.user.create({
      data: {
        email: 'demo-buyer@falah.app',
        name: 'Demo Buyer',
        flhBalance: 50000,
      },
    });
  }
  console.log(`  👤 Buyer: ${buyer.name} (${buyer.email})\n`);

  // ── Define 6 demo listings ────────────────────────────────────────────────
  const listingsData = [
    {
      title: 'Modern React Dashboard',
      description:
        'A fully responsive admin dashboard built with React, TypeScript, and Tailwind CSS. Includes authentication, data visualization charts, dark mode support, and a reusable component library. Perfect for startups and SaaS platforms.',
      category: 'programming-tech',
      subcategory: 'Frontend',
      priceFlh: 15000,
      deliveryDays: 10,
      packages: [
        {
          name: 'Basic',
          description: 'Single-page dashboard with 3 core charts, responsive layout, and basic theming.',
          price: 8000,
          deliveryDays: 7,
          revisions: 2,
        },
        {
          name: 'Standard',
          description: 'Multi-page dashboard with authentication, API integration, 6+ chart types, and dark mode.',
          price: 15000,
          deliveryDays: 10,
          revisions: 3,
        },
        {
          name: 'Premium',
          description: 'Full enterprise dashboard with real-time data, user management, role-based access control, and one-click deployment.',
          price: 30000,
          deliveryDays: 14,
          revisions: 5,
        },
      ],
      tags: ['react', 'typescript', 'tailwind', 'dashboard', 'admin', 'frontend'],
      images: ['https://placehold.co/600x400/3b82f6/white?text=React+Dashboard'],
      salesCount: 12,
      rating: 4.8,
      reviewCount: 8,
    },
    {
      title: 'Flutter Mobile App — MVP Kit',
      description:
        'Cross-platform mobile application built with Flutter and Dart. Includes state management (Riverpod), REST API integration, push notifications, and a clean Material-You design. Works on both iOS and Android.',
      category: 'programming-tech',
      subcategory: 'Mobile App Development',
      priceFlh: 20000,
      deliveryDays: 14,
      packages: [
        {
          name: 'Basic',
          description: 'Single-screen app with 2 core features, basic navigation, and static data.',
          price: 10000,
          deliveryDays: 10,
          revisions: 2,
        },
        {
          name: 'Standard',
          description: 'Multi-screen app with API integration, local storage, push notifications, and 4-6 feature modules.',
          price: 20000,
          deliveryDays: 14,
          revisions: 3,
        },
        {
          name: 'Premium',
          description: 'Full production-ready app with backend integration, CI/CD pipeline, app store submission support, and analytics.',
          price: 40000,
          deliveryDays: 21,
          revisions: 5,
        },
      ],
      tags: ['flutter', 'dart', 'mobile', 'cross-platform', 'android', 'ios'],
      images: ['https://placehold.co/600x400/8b5cf6/white?text=Flutter+App'],
      salesCount: 8,
      rating: 4.6,
      reviewCount: 5,
    },
    {
      title: 'SEO Blog Post Package',
      description:
        'Research-backed, SEO-optimized blog content tailored to your niche. Each article includes keyword research, meta descriptions, internal linking suggestions, and a featured image brief. Plagiarism-free with Grammarly certification.',
      category: 'writing-translation',
      subcategory: 'Content Writing',
      priceFlh: 5000,
      deliveryDays: 3,
      packages: [
        {
          name: 'Basic',
          description: '1 x 800-word blog post with basic keyword optimization and meta description.',
          price: 3000,
          deliveryDays: 2,
          revisions: 1,
        },
        {
          name: 'Standard',
          description: '3 x 1200-word blog posts with comprehensive keyword strategy, headings, and image briefs.',
          price: 8000,
          deliveryDays: 5,
          revisions: 2,
        },
        {
          name: 'Premium',
          description: '6 x 1500-word pillar posts with cluster content strategy, competitor analysis, and social media snippets.',
          price: 15000,
          deliveryDays: 10,
          revisions: 3,
        },
      ],
      tags: ['seo', 'blog', 'content-writing', 'copywriting', 'wordpress'],
      images: ['https://placehold.co/600x400/10b981/white?text=Content+Writing'],
      salesCount: 25,
      rating: 4.9,
      reviewCount: 20,
    },
    {
      title: 'Complete Brand Identity Design',
      description:
        'A comprehensive brand identity package including logo (primary, secondary, icon), color palette, typography system, business card mockup, and brand guidelines PDF. Delivered in AI, EPS, PNG, and SVG formats.',
      category: 'graphics-design',
      subcategory: 'Logo & Brand Identity',
      priceFlh: 18000,
      deliveryDays: 12,
      packages: [
        {
          name: 'Basic',
          description: 'Logo design with 3 concepts, 2 revisions, and final files in PNG and SVG.',
          price: 8000,
          deliveryDays: 7,
          revisions: 2,
        },
        {
          name: 'Standard',
          description: 'Full identity kit: logo + color palette + typography + 2 mockups + brand guidelines PDF.',
          price: 18000,
          deliveryDays: 12,
          revisions: 3,
        },
        {
          name: 'Premium',
          description: 'Complete brand launch: full identity kit + 6 mockups (stationery, signage, social) + vector files + brand strategy document.',
          price: 35000,
          deliveryDays: 18,
          revisions: 5,
        },
      ],
      tags: ['branding', 'logo', 'design', 'identity', 'graphic-design'],
      images: ['https://placehold.co/600x400/f59e0b/white?text=Brand+Identity'],
      salesCount: 15,
      rating: 4.7,
      reviewCount: 11,
    },
    {
      title: 'Full SEO Audit & Optimization',
      description:
        'Technical SEO audit covering site speed, mobile-friendliness, crawlability, indexation, and Core Web Vitals. Includes a prioritized action plan and hands-on implementation of fixes. Compatible with WordPress, Shopify, Webflow, and custom sites.',
      category: 'digital-marketing',
      subcategory: 'Search',
      priceFlh: 12000,
      deliveryDays: 7,
      packages: [
        {
          name: 'Basic',
          description: 'SEO audit report with 10+ checkpoints, Core Web Vitals analysis, and a prioritized fix list.',
          price: 6000,
          deliveryDays: 4,
          revisions: 1,
        },
        {
          name: 'Standard',
          description: 'Audit + hands-on fixes for top 15 issues, meta tag optimization, and schema markup implementation.',
          price: 12000,
          deliveryDays: 7,
          revisions: 2,
        },
        {
          name: 'Premium',
          description: 'Full-site optimization: audit + fixes + content gap analysis + backlink audit + monthly ranking report template.',
          price: 25000,
          deliveryDays: 12,
          revisions: 3,
        },
      ],
      tags: ['seo', 'marketing', 'audit', 'optimization', 'web-vitals'],
      images: ['https://placehold.co/600x400/ef4444/white?text=SEO+Audit'],
      salesCount: 20,
      rating: 4.5,
      reviewCount: 14,
    },
    {
      title: 'Professional Video Editing',
      description:
        'High-quality video editing for YouTube, social media, or corporate use. Includes cutting, color grading, motion graphics, sound design, captions, and intro/outro animation. Delivered in 1080p or 4K.',
      category: 'video-animation',
      subcategory: 'Editing & Post-Production',
      priceFlh: 25000,
      deliveryDays: 10,
      packages: [
        {
          name: 'Basic',
          description: 'Up to 5-minute video: trimming, transitions, background music, and simple text overlays.',
          price: 12000,
          deliveryDays: 5,
          revisions: 2,
        },
        {
          name: 'Standard',
          description: 'Up to 15-minute video: full edit including color grading, motion graphics, captions, and sound design.',
          price: 25000,
          deliveryDays: 10,
          revisions: 3,
        },
        {
          name: 'Premium',
          description: 'Up to 30-minute video: cinematic edit with custom animations, multi-cam sync, advanced VFX, and 4K export.',
          price: 50000,
          deliveryDays: 15,
          revisions: 5,
        },
      ],
      tags: ['video', 'editing', 'production', 'youtube', 'motion-graphics'],
      images: ['https://placehold.co/600x400/ec4899/white?text=Video+Editing'],
      salesCount: 6,
      rating: 5.0,
      reviewCount: 4,
    },
    {
      title: 'Islamic Nasheed — Audio Production',
      description:
        'Professional audio production for Islamic nasheeds, spoken word, and Quran recitation projects. Includes vocal recording, mixing, mastering, and background instrumental arrangement. Delivered in high-quality WAV and MP3 formats with optional music-free versions.',
      category: 'music-audio',
      subcategory: 'Production & Composition',
      priceFlh: 10000,
      deliveryDays: 7,
      packages: [
        {
          name: 'Basic',
          description: '1-track recording: vocal tuning, basic mixing, and MP3 export up to 3 minutes.',
          price: 5000,
          deliveryDays: 5,
          revisions: 2,
        },
        {
          name: 'Standard',
          description: '2-track EP: full recording, mixing, mastering, and instrumental arrangement. Up to 6 minutes total.',
          price: 10000,
          deliveryDays: 7,
          revisions: 3,
        },
        {
          name: 'Premium',
          description: 'Full album production (up to 6 tracks): multi-track recording, advanced mixing & mastering, sound design, and distribution-ready masters.',
          price: 25000,
          deliveryDays: 14,
          revisions: 5,
        },
      ],
      tags: ['nasheed', 'audio', 'production', 'mixing', 'islamic', 'music'],
      images: ['https://placehold.co/600x400/a855f7/white?text=Audio+Production'],
      salesCount: 9,
      rating: 4.8,
      reviewCount: 7,
    },
    {
      title: 'AI Chatbot — Islamic Knowledge Base',
      description:
        'Custom AI chatbot built with LLM integration, trained on Islamic texts, fiqh rulings, and Quranic tafsir. Includes conversation history, context-aware responses, and deployment-ready API. Perfect for Islamic apps, websites, and community platforms.',
      category: 'ai-services',
      subcategory: 'AI Development',
      priceFlh: 25000,
      deliveryDays: 14,
      packages: [
        {
          name: 'Basic',
          description: 'Single-purpose Q&A bot with 50 pre-defined responses and simple keyword matching.',
          price: 12000,
          deliveryDays: 7,
          revisions: 2,
        },
        {
          name: 'Standard',
          description: 'LLM-powered chatbot with Islamic knowledge base (Quran, hadith, fiqh), conversation memory, and web widget deployment.',
          price: 25000,
          deliveryDays: 14,
          revisions: 3,
        },
        {
          name: 'Premium',
          description: 'Full AI assistant platform: multi-persona support (mufti, alim, murabbi), RAG pipeline, analytics dashboard, and API-first architecture.',
          price: 50000,
          deliveryDays: 21,
          revisions: 5,
        },
      ],
      tags: ['ai', 'chatbot', 'islamic', 'llm', 'knowledge-base', 'automation'],
      images: ['https://placehold.co/600x400/06b6d4/white?text=AI+Chatbot'],
      salesCount: 5,
      rating: 4.9,
      reviewCount: 4,
    },
    {
      title: 'Halal Business Strategy Consulting',
      description:
        'Shariah-compliant business consulting for startups and SMEs. Covers business model validation, market analysis, financial planning, and growth strategy — all aligned with Islamic finance principles (no riba, no gharar). Includes a comprehensive strategy document.',
      category: 'consulting',
      subcategory: 'Business Consulting',
      priceFlh: 20000,
      deliveryDays: 10,
      packages: [
        {
          name: 'Basic',
          description: '1-hour strategy call + 5-page business assessment report with key recommendations.',
          price: 8000,
          deliveryDays: 5,
          revisions: 1,
        },
        {
          name: 'Standard',
          description: '3 strategy sessions + full business plan: market analysis, financial projections, and Shariah compliance audit.',
          price: 20000,
          deliveryDays: 10,
          revisions: 2,
        },
        {
          name: 'Premium',
          description: 'End-to-end business launch: strategy, legal structure (Shariah-compliant), fundraising deck, 3-month roadmap, and quarterly check-ins.',
          price: 45000,
          deliveryDays: 21,
          revisions: 4,
        },
      ],
      tags: ['consulting', 'business', 'shariah', 'strategy', 'startup'],
      images: ['https://placehold.co/600x400/64748b/white?text=Consulting'],
      salesCount: 11,
      rating: 4.7,
      reviewCount: 9,
    },
    {
      title: 'Data Analytics Dashboard — Google Looker Studio',
      description:
        'Custom data analytics dashboard built in Google Looker Studio (or open-source Metabase). Includes data source integration, real-time visualizations, KPI tracking, and automated weekly reports. Perfect for e-commerce, SaaS, and marketplace platforms.',
      category: 'data',
      subcategory: 'Data Analytics',
      priceFlh: 12000,
      deliveryDays: 7,
      packages: [
        {
          name: 'Basic',
          description: 'Single-source dashboard with 5 core KPIs, 3 visualization pages, and weekly email report.',
          price: 6000,
          deliveryDays: 5,
          revisions: 2,
        },
        {
          name: 'Standard',
          description: 'Multi-source dashboard (up to 3 data sources), 10+ KPIs, custom date filters, and automated Slack/email reports.',
          price: 12000,
          deliveryDays: 7,
          revisions: 3,
        },
        {
          name: 'Premium',
          description: 'Full analytics suite: unlimited data sources, advanced calculated metrics, user-level permissions, embedded dashboards, and API access.',
          price: 25000,
          deliveryDays: 14,
          revisions: 5,
        },
      ],
      tags: ['data', 'analytics', 'dashboard', 'looker', 'metabase', 'kpi'],
      images: ['https://placehold.co/600x400/14b8a6/white?text=Data+Dashboard'],
      salesCount: 14,
      rating: 4.6,
      reviewCount: 10,
    },
    {
      title: 'E-Commerce Store — Shopify & WooCommerce',
      description:
        'Full e-commerce store setup on Shopify or WooCommerce with halal-compliant product catalog, payment gateway integration, shipping configuration, and SEO optimization. Includes theme customization, product import (up to 100 items), and staff training.',
      category: 'business',
      subcategory: 'E-Commerce',
      priceFlh: 18000,
      deliveryDays: 10,
      packages: [
        {
          name: 'Basic',
          description: 'Store setup: theme installation, 20 product listings, payment gateway, and basic SEO.',
          price: 8000,
          deliveryDays: 5,
          revisions: 2,
        },
        {
          name: 'Standard',
          description: 'Full store: custom theme tweaks, 50 product listings, shipping zones, tax rules, email marketing integration, and Google Analytics.',
          price: 18000,
          deliveryDays: 10,
          revisions: 3,
        },
        {
          name: 'Premium',
          description: 'Enterprise store: 100+ products, multi-currency, multi-language, custom features, abandoned cart recovery, loyalty program, and 1-month support.',
          price: 35000,
          deliveryDays: 18,
          revisions: 5,
        },
      ],
      tags: ['ecommerce', 'shopify', 'woocommerce', 'store', 'halal', 'business'],
      images: ['https://placehold.co/600x400/6366f1/white?text=E-Commerce'],
      salesCount: 18,
      rating: 4.8,
      reviewCount: 15,
    },
    {
      title: 'Life Coaching — Islamic Personal Development',
      description:
        'Personalized life coaching grounded in Islamic principles of self-development (tazkiyah). Includes goal setting, habit tracking, time management (barakah-based), and spiritual growth planning. Sessions available via video call or chat.',
      category: 'personal-growth',
      subcategory: 'Self Improvement',
      priceFlh: 8000,
      deliveryDays: 3,
      packages: [
        {
          name: 'Basic',
          description: '1 x 45-min coaching session + personalized action plan with 3 key goals.',
          price: 4000,
          deliveryDays: 2,
          revisions: 1,
        },
        {
          name: 'Standard',
          description: '4 weekly sessions + habit tracking spreadsheet + daily WhatsApp check-ins + mid-program review.',
          price: 12000,
          deliveryDays: 28,
          revisions: 2,
        },
        {
          name: 'Premium',
          description: '3-month program: 12 sessions + comprehensive personality assessment + Quran journal + group accountability circle + lifetime resources.',
          price: 30000,
          deliveryDays: 90,
          revisions: 4,
        },
      ],
      tags: ['coaching', 'personal-development', 'tazkiyah', 'islamic', 'growth'],
      images: ['https://placehold.co/600x400/65a30d/white?text=Life+Coaching'],
      salesCount: 22,
      rating: 4.9,
      reviewCount: 18,
    },
    {
      title: 'Product Photography — Halal E-Commerce Ready',
      description:
        'Professional product photography optimized for e-commerce marketplaces. Each product is shot on a clean background with proper lighting, color correction, and retouching. Includes white-background and lifestyle-style options. Delivered in web-optimized and print-ready formats.',
      category: 'photography',
      subcategory: 'Product Photography',
      priceFlh: 7000,
      deliveryDays: 5,
      packages: [
        {
          name: 'Basic',
          description: '5 product photos: white background, basic color correction, and web-optimized export.',
          price: 3500,
          deliveryDays: 3,
          revisions: 1,
        },
        {
          name: 'Standard',
          description: '15 product photos: white + 1 lifestyle setup, advanced retouching, shadow effects, and multiple formats.',
          price: 7000,
          deliveryDays: 5,
          revisions: 2,
        },
        {
          name: 'Premium',
          description: '30 product photos: multiple angles, 2 lifestyle setups, 360-degree view, video clip per product, and brand style guide integration.',
          price: 15000,
          deliveryDays: 10,
          revisions: 3,
        },
      ],
      tags: ['photography', 'product', 'ecommerce', 'food', 'retouching'],
      images: ['https://placehold.co/600x400/f97316/white?text=Photography'],
      salesCount: 30,
      rating: 4.7,
      reviewCount: 22,
    },
    {
      title: 'Halal Bookkeeping & Financial Reporting',
      description:
        'Shariah-compliant bookkeeping and financial reporting services for small businesses and freelancers. Includes income/expense tracking, profit calculation (zakat-ready), invoice management, and monthly financial statements. Uses accounting software (Xero, QuickBooks, or Wave).',
      category: 'finance',
      subcategory: 'Accounting',
      priceFlh: 10000,
      deliveryDays: 7,
      packages: [
        {
          name: 'Basic',
          description: 'Monthly bookkeeping: up to 50 transactions, income statement, and expense categorization.',
          price: 5000,
          deliveryDays: 5,
          revisions: 1,
        },
        {
          name: 'Standard',
          description: 'Monthly bookkeeping + quarterly financial statements + zakat calculation + GST/SST preparation.',
          price: 12000,
          deliveryDays: 7,
          revisions: 2,
        },
        {
          name: 'Premium',
          description: 'Full financial management: weekly bookkeeping, monthly statements, annual audit support, tax filing, cash flow forecasting, and dedicated finance advisor.',
          price: 30000,
          deliveryDays: 14,
          revisions: 4,
        },
      ],
      tags: ['finance', 'accounting', 'bookkeeping', 'zakat', 'halal', 'tax'],
      images: ['https://placehold.co/600x400/eab308/white?text=Financial+Services'],
      salesCount: 16,
      rating: 4.8,
      reviewCount: 13,
    },
  ];

  // ── Clean up existing seed data for idempotency ───────────────────────────
  console.log('  🧹 Clearing previous seed data...');
  await prisma.review.deleteMany({});
  await prisma.purchase.deleteMany({});
  await prisma.listing.deleteMany({});

  // ── Create listings ───────────────────────────────────────────────────────
  console.log('  📦 Creating listings...');
  const createdListings: Array<{ id: string; title: string }> = [];

  for (const data of listingsData) {
    const listing = await prisma.listing.create({
      data: {
        title: data.title,
        description: data.description,
        category: data.category,
        subcategory: data.subcategory,
        priceFlh: data.priceFlh,
        packages: JSON.stringify(data.packages),
        tags: JSON.stringify(data.tags),
        images: JSON.stringify(data.images),
        deliveryDays: data.deliveryDays,
        rating: data.rating,
        reviewCount: data.reviewCount,
        salesCount: data.salesCount,
        sellerId: seller.id,
        status: 'active',
        featured: false,
      },
    });
    createdListings.push({ id: listing.id, title: listing.title });
    console.log(`    ✅ ${listing.title}`);
  }

  // ── Create a demo purchase (so we can create a review) ────────────────────
  console.log('\n  🛒 Creating demo purchase...');
  const firstListing = createdListings[0];
  const purchase = await prisma.purchase.create({
    data: {
      listingId: firstListing.id,
      buyerId: buyer.id,
      sellerId: seller.id,
      packageName: 'Standard',
      amountFlh: 15000,
      platformFee: 1500,
      sellerPayout: 13500,
      status: 'completed',
      autoConfirmAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // auto-confirm in 7 days
    },
  });
  console.log(`    ✅ Purchase for "${firstListing.title}" (Standard package)`);

  // ── Create a demo review ──────────────────────────────────────────────────
  console.log('\n  ⭐ Creating demo review...');
  const review = await prisma.review.create({
    data: {
      listingId: firstListing.id,
      purchaseId: purchase.id,
      reviewerId: buyer.id,
      sellerId: seller.id,
      rating: 5,
      title: 'Exceptional quality and professionalism!',
      text: 'The developer delivered a polished dashboard that exceeded expectations. Clean TypeScript code, thorough documentation, and great communication throughout. Highly recommended for any React project.',
    },
  });
  console.log(`    ✅ Review (${review.rating}★) on "${firstListing.title}"`);

  // ── Summary ───────────────────────────────────────────────────────────────
  console.log('\n' + '═'.repeat(50));
  console.log('🎉 Souq seed completed successfully!');
  console.log(`   • ${createdListings.length} listings created`);
  console.log(`   • 1 purchase created`);
  console.log(`   • 1 review created`);
  console.log(`   • Seller: ${seller.name} (${seller.email})`);
  console.log(`   • Buyer: ${buyer.name} (${buyer.email})`);
  console.log('═'.repeat(50));
}

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