import { NextRequest, NextResponse } from "next/server";
import bcrypt from "bcryptjs";
import { prisma } from "@/lib/prisma";

export async function POST(req: NextRequest) {
  try {
    // Require ADMIN_SECRET to prevent unauthorized seeding
    const adminSecret = process.env.ADMIN_SECRET;
    const providedSecret = req.headers.get("x-admin-secret") || req.headers.get("authorization")?.replace("Bearer ", "");
    if (adminSecret && providedSecret !== adminSecret) {
      return NextResponse.json(
        { error: "Unauthorized — valid admin secret required" },
        { status: 401 }
      );
    }
    // ── 1. Seed Demo Users ──────────────────────────────────────────
    const users = [
      {
        email: "demo@falahos.my",
        password: "password123",
        name: "Demo User",
        flhBalance: 10000,
        isPremium: true,
        isPro: false,
        trialEndsAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
        preferredName: "Demo",
        coachingGoals: "Learn more about Islam and improve my daily prayers",
      },
      {
        email: "premium@falahos.my",
        password: "Premium123!",
        name: "Premium Demo",
        flhBalance: 50000,
        isPremium: true,
        isPro: false,
        preferredName: "Premium",
        coachingGoals: "Advanced Islamic studies and community leadership",
      },
    ];

    const userResults = [];

    for (const user of users) {
      const { password, ...userData } = user;
      const passwordHash = await bcrypt.hash(password, 12);

      const upserted = await prisma.user.upsert({
        where: { email: user.email },
        update: { ...userData, passwordHash },
        create: { ...userData, passwordHash },
      });

      userResults.push({ email: upserted.email, id: upserted.id });
    }

    // Find demo user for sample data
    const demoUser = await prisma.user.findUnique({ where: { email: "demo@falahos.my" } });
    const premiumUser = await prisma.user.findUnique({ where: { email: "premium@falahos.my" } });
    const demoId = demoUser!.id;
    const premiumId = premiumUser!.id;

    // ── 2. Seed Forum Categories ─────────────────────────────────────
    const categoriesData = [
      { name: "General Discussion", description: "General Islamic discussions and community topics", icon: "💬", order: 1 },
      { name: "Quran & Tafsir", description: "Quranic studies, recitation, and interpretation", icon: "📖", order: 2 },
      { name: "Fiqh & Hadith", description: "Islamic jurisprudence and prophetic traditions", icon: "📜", order: 3 },
      { name: "Family & Marriage", description: "Family life, marriage, and parenting in Islam", icon: "👨‍👩‍👧‍👦", order: 4 },
      { name: "Halal Lifestyle", description: "Halal food, travel, fashion, and daily living", icon: "🌿", order: 5 },
      { name: "Community Events", description: "Local events, study circles, and gatherings", icon: "📅", order: 6 },
    ];

    const categoriesCreated: string[] = [];
    for (const cat of categoriesData) {
      const created = await prisma.forumCategory.upsert({
        where: { name: cat.name },
        update: cat,
        create: cat,
      });
      categoriesCreated.push(created.name);
    }

    // ── 3. Seed Sample Forum Threads ─────────────────────────────────
    const generalCat = await prisma.forumCategory.findUnique({ where: { name: "General Discussion" } });
    const quranCat = await prisma.forumCategory.findUnique({ where: { name: "Quran & Tafsir" } });

    if (generalCat) {
      await prisma.forumThread.upsert({
        where: { id: "seed-thread-welcome" },
        update: {},
        create: {
          id: "seed-thread-welcome",
          title: "Welcome to Falah Community! 👋",
          content: "Assalamu alaikum everyone! This is our community space where we can discuss all things related to Islam, seek knowledge, and support each other. Feel free to introduce yourself!",
          categoryId: generalCat.id,
          authorId: premiumId,
          pinned: true,
          shariahStatus: "approved",
        },
      });
    }

    if (quranCat) {
      await prisma.forumThread.upsert({
        where: { id: "seed-thread-quran" },
        update: {},
        create: {
          id: "seed-thread-quran",
          title: "Daily Quran Reflection — Surah Al-Fatiha",
          content: "Let's reflect on Surah Al-Fatiha together. What does 'Guide us to the straight path' mean to you in your daily life? Share your reflections below.",
          categoryId: quranCat.id,
          authorId: demoId,
          pinned: false,
          shariahStatus: "approved",
        },
      });
    }

    // ── 4. Seed Sample Group (Private Forum) ─────────────────────────
    const group = await prisma.group.upsert({
      where: { id: "seed-group-study-circle" },
      update: {},
      create: {
        id: "seed-group-study-circle",
        name: "Quran Study Circle",
        description: "A private group for dedicated Quran study and memorization. Members meet weekly to review progress.",
        ownerId: premiumId,
        inviteCode: "QURAN2026",
        members: {
          create: [
            { userId: premiumId, role: "owner" },
            { userId: demoId, role: "member" },
          ],
        },
      },
      include: { _count: { select: { members: true, threads: true } } },
    });

    // Create a thread in the group
    const groupCat = generalCat || quranCat;
    if (groupCat) {
      await prisma.forumThread.upsert({
        where: { id: "seed-thread-group-intro" },
        update: {},
        create: {
          id: "seed-thread-group-intro",
          title: "Welcome to Quran Study Circle 📖",
          content: "Assalamu alaikum group members! This is our private space for discussing our weekly Quran study sessions. Our first session will cover Surah Al-Kahf — please review the tafsir beforehand.",
          categoryId: groupCat.id,
          authorId: premiumId,
          groupId: group.id,
          pinned: true,
          shariahStatus: "approved",
        },
      });
    }

    // ── 5. Seed Sample Marketplace Listings ──────────────────────────
    const listingsData = [
      {
        id: "seed-listing-tafsir",
        title: "Tafsir Ibn Kathir (Abridged) — 10 Volumes",
        description: "Complete set of Tafsir Ibn Kathir in English. Excellent condition, hardly used. Perfect for anyone looking to deepen their understanding of the Quran.",
        category: "Books",
        priceFlh: 2500,
        sellerId: premiumId,
        featured: true,
      },
      {
        id: "seed-listing-prayer-mat",
        title: "Premium Turkish Prayer Mat — Green",
        description: "High-quality woven Turkish prayer mat with mosque design. Soft texture, perfect size. Ideal gift for loved ones.",
        category: "Essentials",
        priceFlh: 800,
        sellerId: demoId,
        featured: false,
      },
      {
        id: "seed-listing-miswak",
        title: "Natural Miswak Sticks (Pack of 10)",
        description: "Fresh, high-quality miswak sticks from the Arak tree. Naturally whitens teeth, freshens breath, and follows the Sunnah. Each pack contains 10 sticks.",
        category: "Wellness",
        priceFlh: 150,
        sellerId: demoId,
        featured: false,
      },
      {
        id: "seed-listing-hijab",
        title: "Handcrafted Silk Hijabs — Assorted Colors",
        description: "Beautiful handcrafted silk hijabs in assorted colors. Lightweight, breathable fabric. Perfect for daily wear or special occasions.",
        category: "Fashion",
        priceFlh: 350,
        sellerId: premiumId,
        featured: false,
      },
    ];

    const listingsCreated: string[] = [];
    for (const listing of listingsData) {
      await prisma.listing.upsert({
        where: { id: listing.id },
        update: { ...listing },
        create: listing,
      });
      listingsCreated.push(listing.title);
    }

    return NextResponse.json(
      {
        message: "Seed completed successfully",
        users: userResults,
        categories: categoriesCreated,
        group: { name: group.name, members: group._count.members },
        listings: listingsCreated,
        credentials: [
          { email: "demo@falahos.my", password: "password123" },
          { email: "premium@falahos.my", password: "Premium123!" },
        ],
      },
      { status: 200 }
    );
  } catch (error) {
    console.error("Seed error:", error);
    return NextResponse.json(
      { error: "Seeding failed. Please try again." },
      { status: 500 }
    );
  }
}
