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

const prisma = new PrismaClient();

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

  // ── Admin User ──────────────────────────────────────────────
  const adminHash = await bcrypt.hash('Admin123!', 12);
  const admin = await prisma.user.upsert({
    where: { email: 'admin@theketobay.com' },
    update: {},
    create: {
      email: 'admin@theketobay.com',
      passwordHash: adminHash,
      name: 'Admin',
      role: 'ADMIN',
      subscriptionTier: 'LIFETIME',
      subscriptionStatus: 'ACTIVE'
    }
  });
  console.log('✅ Admin user created:', admin.email);

  // ── Blog Categories ─────────────────────────────────────────
  const categories = await Promise.all([
    prisma.blogCategory.upsert({ where: { slug: 'beginner-guide' }, update: {}, create: { name: 'Beginner Guide', slug: 'beginner-guide' } }),
    prisma.blogCategory.upsert({ where: { slug: 'recipes' }, update: {}, create: { name: 'Keto Recipes', slug: 'recipes' } }),
    prisma.blogCategory.upsert({ where: { slug: 'science' }, update: {}, create: { name: 'Keto Science', slug: 'science' } }),
    prisma.blogCategory.upsert({ where: { slug: 'tips' }, update: {}, create: { name: 'Tips & Tricks', slug: 'tips' } }),
  ]);
  console.log('✅ Blog categories created');

  // ── Keto Plans ──────────────────────────────────────────────
  const plans = [
    {
      slug: '3-day-keto-starter',
      title: '3-Day Keto Starter Plan',
      description: 'The perfect introduction to ketogenic eating. This free 3-day plan eases you into keto with delicious, simple meals that are easy to prepare.',
      shortDesc: 'Perfect for beginners. Free 3-day introduction to keto eating.',
      duration: 'THREE_DAYS' as const,
      price: 0,
      tier: 'FREE' as const,
      featured: true,
      published: true,
      meals: {
        days: [
          {
            day: 1,
            meals: {
              breakfast: { name: 'Bulletproof Coffee + Scrambled Eggs', description: '3 eggs scrambled in butter with 1 tbsp cream cheese, Bulletproof coffee with MCT oil', calories: 520, proteinG: 24, fatG: 45, netCarbsG: 2 },
              lunch: { name: 'Chicken Caesar Salad (no croutons)', description: 'Grilled chicken breast, romaine, parmesan, sugar-free Caesar dressing', calories: 480, proteinG: 42, fatG: 32, netCarbsG: 4 },
              dinner: { name: 'Salmon with Asparagus', description: 'Pan-seared salmon fillet, roasted asparagus with garlic butter', calories: 580, proteinG: 45, fatG: 42, netCarbsG: 5 },
              snack: { name: 'String Cheese + Almonds', description: '2 string cheese sticks + 20g almonds', calories: 220, proteinG: 12, fatG: 18, netCarbsG: 2 }
            }
          }
        ]
      },
      shoppingList: {
        proteins: ['Eggs (1 dozen)', 'Chicken breast (500g)', 'Salmon fillet (2x)'],
        fats: ['Butter', 'MCT oil', 'Olive oil', 'String cheese', 'Almonds'],
        vegetables: ['Romaine lettuce', 'Asparagus', 'Spinach'],
        other: ['Parmesan', 'Caesar dressing (sugar-free)', 'Cream cheese']
      }
    },
    {
      slug: '7-day-fat-burn-keto',
      title: '7-Day Fat Burn Keto Plan',
      description: 'Our most popular program. A complete week of keto meals designed for maximum fat burning, with detailed recipes, macro counts, and a full shopping list.',
      shortDesc: 'Our most popular 7-day program. Maximum fat burning, 4 meals/day.',
      duration: 'SEVEN_DAYS' as const,
      price: 19.99,
      tier: 'PAID' as const,
      featured: true,
      published: true,
      meals: { days: [] }, // Full content in production
      shoppingList: { proteins: [], fats: [], vegetables: [], other: [] }
    },
    {
      slug: '14-day-keto-transformation',
      title: '14-Day Keto Transformation',
      description: 'A comprehensive two-week program for those serious about keto. Includes progressive meal variations, intermittent fasting integration, and detailed nutrition science.',
      shortDesc: 'Two-week deep keto protocol with IF integration. For serious results.',
      duration: 'FOURTEEN_DAYS' as const,
      price: 29.99,
      tier: 'PAID' as const,
      featured: true,
      published: true,
      meals: { days: [] },
      shoppingList: { proteins: [], fats: [], vegetables: [], other: [] }
    },
    {
      slug: '30-day-keto-mastery',
      title: '30-Day Keto Mastery Program',
      description: 'The ultimate keto experience. A full month of diverse, delicious meals organized by week with increasing complexity. Includes keto adaptation guide, electrolyte protocol, and exercise tips.',
      shortDesc: 'The complete 30-day keto journey. Every meal planned, nothing left to chance.',
      duration: 'THIRTY_DAYS' as const,
      price: 47.00,
      tier: 'PAID' as const,
      featured: false,
      published: true,
      meals: { days: [] },
      shoppingList: { proteins: [], fats: [], vegetables: [], other: [] }
    }
  ];

  for (const plan of plans) {
    await prisma.ketoPlan.upsert({
      where: { slug: plan.slug },
      update: {},
      create: plan as any
    });
  }
  console.log('✅ Keto plans created');

  // ── Products ────────────────────────────────────────────────
  const products = [
    { slug: 'mct-oil-pure', name: 'Pure MCT Oil (500ml)', description: 'C8/C10 MCT oil for rapid ketone production. Unflavored, perfect for coffee and cooking.', affiliateUrl: 'https://amazon.com', priceDisplay: '$24.99', category: 'SUPPLEMENTS' as const, tags: ['keto-friendly', 'beginner', 'energy'], featured: true },
    { slug: 'electrolyte-keto', name: 'Keto Electrolyte Complex', description: 'Complete electrolyte blend with sodium, potassium, magnesium. Prevents keto flu.', affiliateUrl: 'https://amazon.com', priceDisplay: '$29.99', category: 'SUPPLEMENTS' as const, tags: ['keto-friendly', 'beginner'], featured: true },
    { slug: 'keto-snack-bars', name: 'Keto Protein Bars (12 pack)', description: '2g net carbs per bar. Real chocolate flavor without kicking you out of ketosis.', affiliateUrl: 'https://amazon.com', priceDisplay: '$34.99', category: 'SNACKS' as const, tags: ['keto-friendly', 'snack'], featured: true },
    { slug: 'macadamia-butter', name: 'Macadamia Nut Butter', description: 'Creamy macadamia butter — the perfect high-fat keto snack. No added sugar.', affiliateUrl: 'https://amazon.com', priceDisplay: '$18.99', category: 'SNACKS' as const, tags: ['keto-friendly', 'fat'], featured: true },
    { slug: 'ketone-strips', name: 'Ketone Test Strips (100 pack)', description: 'Urine ketone test strips to verify you\'re in ketosis. Easy and affordable.', affiliateUrl: 'https://amazon.com', priceDisplay: '$12.99', category: 'SUPPLEMENTS' as const, tags: ['beginner', 'testing'], featured: false },
    { slug: 'avocado-oil', name: 'Pure Avocado Oil (1L)', description: 'High smoke point avocado oil for keto cooking. Neutral taste, ideal for all cooking methods.', affiliateUrl: 'https://amazon.com', priceDisplay: '$19.99', category: 'INGREDIENTS' as const, tags: ['keto-friendly', 'cooking'], featured: false },
  ];

  for (const product of products) {
    await prisma.product.upsert({ where: { slug: product.slug }, update: {}, create: product as any });
  }
  console.log('✅ Products created');

  // ── Blog Posts ──────────────────────────────────────────────
  const posts = [
    {
      slug: 'keto-diet-beginners-guide',
      title: 'The Complete Keto Diet Guide for Beginners (2026)',
      excerpt: 'Everything you need to know to start keto safely and effectively. From macros to meal planning.',
      content: '<h2>What is Keto?</h2><p>The ketogenic diet is a high-fat, low-carb eating approach...</p>',
      published: true, featured: true, categoryId: categories[0].id,
      tags: ['beginner', 'guide', 'keto basics'], readingTime: 12,
      metaTitle: 'Keto Diet for Beginners: Complete 2026 Guide',
      metaDesc: 'Learn everything about starting keto: macros, foods, meal planning, and avoiding keto flu.',
      publishedAt: new Date()
    },
    {
      slug: 'keto-flu-symptoms-prevention',
      title: 'Keto Flu: Symptoms, Causes and How to Prevent It',
      excerpt: 'The keto flu affects most beginners. Learn exactly why it happens and how to eliminate it completely.',
      content: '<h2>What is Keto Flu?</h2><p>Keto flu is a collection of symptoms...</p>',
      published: true, featured: false, categoryId: categories[0].id,
      tags: ['beginner', 'keto flu', 'electrolytes'], readingTime: 7,
      publishedAt: new Date()
    },
    {
      slug: 'best-keto-snacks-2026',
      title: '25 Best Keto Snacks Under 5g Net Carbs',
      excerpt: 'Never be caught hungry again. These portable, delicious keto snacks keep you in ketosis on the go.',
      content: '<h2>Why Keto Snacks Matter</h2><p>Staying in ketosis requires planning...</p>',
      published: true, featured: true, categoryId: categories[1].id,
      tags: ['snacks', 'recipes', 'easy'], readingTime: 8,
      publishedAt: new Date()
    }
  ];

  for (const post of posts) {
    await prisma.blogPost.upsert({ where: { slug: post.slug }, update: {}, create: post });
  }
  console.log('✅ Blog posts created');

  // ── Achievements ─────────────────────────────────────────────
  const achievements = [
    { slug: 'first-log', name: 'First Step', description: 'Logged your first meal', icon: '📝', points: 10, condition: { type: 'logs', value: 1 } },
    { slug: 'streak-7', name: 'Keto Week', description: '7-day streak achieved!', icon: '🔥', points: 50, condition: { type: 'streak', value: 7 } },
    { slug: 'streak-14', name: 'Keto Fortnight', description: '14-day streak!', icon: '💪', points: 100, condition: { type: 'streak', value: 14 } },
    { slug: 'streak-30', name: 'Keto Warrior', description: '30-day streak legend!', icon: '⚔️', points: 250, condition: { type: 'streak', value: 30 } },
    { slug: 'first-purchase', name: 'Investor', description: 'Purchased your first keto plan', icon: '💰', points: 25, condition: { type: 'purchases', value: 1 } },
    { slug: 'logs-10', name: 'Consistent', description: 'Logged 10 days of nutrition', icon: '📊', points: 75, condition: { type: 'logs', value: 10 } },
    { slug: 'logs-30', name: 'Data Driven', description: '30 days of consistent tracking', icon: '🎯', points: 200, condition: { type: 'logs', value: 30 } },
  ];

  for (const achievement of achievements) {
    await prisma.achievement.upsert({ where: { slug: achievement.slug }, update: {}, create: achievement as any });
  }
  console.log('✅ Achievements created');

  // ── Sample Coupon ────────────────────────────────────────────
  await prisma.coupon.upsert({
    where: { code: 'WELCOME20' },
    update: {},
    create: { code: 'WELCOME20', discountType: 'PERCENTAGE', discountValue: 20, maxUses: 100, active: true }
  });
  await prisma.coupon.upsert({
    where: { code: 'TELEGRAM10' },
    update: {},
    create: { code: 'TELEGRAM10', discountType: 'PERCENTAGE', discountValue: 10, active: true }
  });
  console.log('✅ Coupons created: WELCOME20, TELEGRAM10');

  console.log('\n🥑 Seed complete! TheKetoBay is ready.');
  console.log('   Admin: admin@theketobay.com / Admin123!');
}

main()
  .catch(e => { console.error(e); process.exit(1); })
  .finally(() => prisma.$disconnect());
